This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for TypeScript puzzle on BFE.dev
5. implement Pick<T, K>
Here's a possible implementation of MyPick<T, K>
:
type MyPick<T, K extends keyof T> = { [P in K]: T[P]}
Explanation:
- We use the
keyof T
operator to get a union type of all keys inT
. - We constrain
K
to be a subset of this union type using theextends
keyword. - We define a mapped type using the
in
keyword, where we iterate over all keysP
inK
. - For each key
P
, we use an index type queryT[P]
to get the type of the corresponding property inT
. - We use this type to define a new property in the resulting type, with the same key
P
. The resulting value type isT[P]
.
Note that this implementation creates a new type by picking properties from T
based on their keys in K
. This means that if K
is empty, the resulting type will also be empty. Additionally, if any key in K
is not a valid key in T
, then the resulting type will be an error.