Pick
Problem - On Github
The aim is to build the inbuilt Pick
utility type.
Out initial type given by the puzzle creator is
type MyPick<T, K> = any
Solution
Lets break this down into a few steps:
1. We want to return an object type
This is simply done by making the type an object
type MyPick<T, K> = { /* Keys Go Here*/ }
2. We want the object keys set from the picked keys type
The keys are passed in through the K
generic, so we should set the new object types keys based on this. We do this through the index signature of our object.
type MyPick<T, K> = {
[Key in K]: /* Values Go Here */
}
3. We want the object value set from the original object.
So we have an object with the right keys, now we just need the right values. We can use the new Key
generic to index the initial object stored in T
.
type MyPick<T, K> = {
[Key in K]: T[Key];
}
4. Cause an error for invalid keys
The type we have now does most of what we want. We do get back a valid object with only the keys we pass in, but we also want to validate that only keys in the T
object are used. This can help us out if we pass in the incorrect object.
All we need to do is make sure that K
extends one of the keys of T
, as shown below.
type MyPick<T, K extends keyof T> = {
[Key in K]: T[Key];
}
What to read more? Check out more posts below!