Skip to main content

Pick

introduction#

Implement the built-in Pick<T, K> generic without using it.

Constructs a type by picking the set of properties K from T

For example

ts
interface Todo {
title: string;
description: string;
completed: boolean;
}
type MyPick<T, K> = any;
type TodoPreview = MyPick<Todo, 'title' | 'completed'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
};
ts
interface Todo {
title: string;
description: string;
completed: boolean;
}
type MyPick<T, K> = any;
type TodoPreview = MyPick<Todo, 'title' | 'completed'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
};
View on GitHub

start point#

ts
/* _____________ Your Code Here _____________ */
type MyPick<T, K> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<Expected1, MyPick<Todo, 'title'>>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Expected2, MyPick<Todo, 'title' | 'completed'>>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
 
interface Todo {
title: string;
description: string;
completed: boolean;
}
 
interface Expected1 {
title: string;
}
 
interface Expected2 {
title: string;
completed: boolean;
}
Try
ts
/* _____________ Your Code Here _____________ */
type MyPick<T, K> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<Expected1, MyPick<Todo, 'title'>>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Expected2, MyPick<Todo, 'title' | 'completed'>>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
 
interface Todo {
title: string;
description: string;
completed: boolean;
}
 
interface Expected1 {
title: string;
}
 
interface Expected2 {
title: string;
completed: boolean;
}
Try
Take the Challenge

my solution#

Spoiler warning // Click to reveal answer
ts
type MyPick<T, K extends keyof T> = {
[Key in K]: T[Key];
};
Try
ts
type MyPick<T, K extends keyof T> = {
[Key in K]: T[Key];
};
Try
Checkout more Solutions