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 Toperator to get a union type of all keys inT. - We constrain
Kto be a subset of this union type using theextendskeyword. - We define a mapped type using the
inkeyword, where we iterate over all keysPinK. - 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.