Yuzhe's Blog

yuzhes

0004 · Pick

0004 · Pick

Challenge Link

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:

  1. K extends keyof T — constrains K to be a subset of T’s keys
  2. [P in K] — iterates over every key P in K
  3. T[P] — looks up the value type of key P in T

The result is a new object type containing only the properties specified in K.

Key concepts: