0004 · Pick
Less than 1 minuteTC-Easy
0004 · Pick
Problem
Implement the built-in Pick<T, K> generic without using it.
Constructs a type by picking the set of properties K from T.
interface Todo {
title: string
description: string
completed: boolean
}
type TodoPreview = MyPick<Todo, 'title' | 'completed'>
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
}Solution
type MyPick<T, K extends keyof T> = { [P in K]: T[P] }Explanation
We use a Mapped Type to iterate over each key P in K and look up its value type T[P].
The key constraint is K extends keyof T — this ensures K only contains keys that actually exist in T. Without this constraint, TypeScript would complain that P cannot be used to index T (since K might include keys that don't exist on T).
Step by step:
K extends keyof T— constrainsKto be a subset ofT's keys[P in K]— iterates over every keyPinKT[P]— looks up the value type of keyPinT
The result is a new object type containing only the properties specified in K.
Key concepts:
- Mapped Types — create new types by transforming properties of an existing type
keyof T— produces a union of all keys ofT
