03 · TypeScript Type Gymnastics
easycodingtypescript~6 min

Implement Pick<T, K>

Objective: Use `keyof` constraints and mapped types, and see how modifiers are preserved.

Re-implement the built-in Pick as MyPick. Your code is type-checked with strict mode against hidden assertions. Fix every compiler error and make the assertions pass.

  • MyPick<T, K> keeps only the keys K from T.
  • K must be constrained to keys of T (invalid keys are a compile error).
  • readonly and optional modifiers are preserved.
MyPick<{ a: 1; b: 2; c: 3 }, 'a' | 'c'>
→ { a: 1; c: 3 }
TypeScript (strict)

⌘/Ctrl + Enter to type-check · Esc then Tab leaves the editor

Output
> Nothing has run yet.
Interview follow-up questions
  • How would you implement Omit with the same tools?
  • Why does the constraint also make this a homomorphic mapped type?
  • When would you write your own utility type instead of using the built-in?