Pick - TypeScript Challenge Explained

Saturday, March 11, 2023

My solution to the Pick TypeScript Challenge as part of my journey to Understanding the TypeScript Challenges.

The MyPick generic type is a custom version of the native Pick generic function. Given a type T and a union of keys K, the generic function should return only those specified in K.

1type MyPick<T, K extends keyof T> = {
2  [P in K]: T[P]
3}
4
5// useage
6
7type Result = MyPick<PersonType, "name" | "age" | "height">
8
9// { "name": string; "age": number; "height": number; }
  • T - The type we will "pick" keys from
  • K - A union of keys to pick e.g. "name" | "age" | "height". We can restrain these keys to values which exist on T by using K extends keyof T.
  • { ... } - Return a record/object type
  • [P in K] - Iterate over each of the keys in K
  • T[P] - Select the value from the original type T for the each key P e.g. When P = "name" we will lookup T["name"] and use the original type it had been assigned = "string"

Other posts


Tagged with: