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 fromK
- A union of keys to pick e.g."name" | "age" | "height"
. We can restrain these keys to values which exist onT
by usingK extends keyof T
.{ ... }
- Return a record/object type[P in K]
- Iterate over each of the keys inK
T[P]
- Select the value from the original typeT
for the each keyP
e.g. WhenP = "name"
we will lookupT["name"]
and use the original type it had been assigned ="string"