Pick - TypeScript Challenge Explained
Mar 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.
type MyPick<T, K extends keyof T> = {
[P in K]: T[P]
}
// useage
type Result = MyPick<PersonType, "name" | "age" | "height">
// { "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 onTby usingK extends keyof T.{ ... }- Return a record/object type[P in K]- Iterate over each of the keys inKT[P]- Select the value from the original typeTfor the each keyPe.g. WhenP = "name"we will lookupT["name"]and use the original type it had been assigned ="string"