First challenge is Pick
It’s usually used when you need to declare the type which is based on another type. And you know in advance which keys are included.
First, you need to iterate over an object
T. Usually Mapped Types are used in this case:
keyof Tgets the keys from the object
inis for iteration over the keys
Keyis a key itself
T[Key]is a value for a specified Key
Second, to iterate over the part of an object, we need to specify
Keys to iterate over:
But with this you have 2 errors:
Type 'Keys' is not assignable to type 'string | number | symbol'
Type 'Key' cannot be used to index type 'T'
Both errors are connected with the rules of the iteration:
- Key can be
- We cannot call
Keydoesn’t exist in
If rule 2 is true, rule 1 will be true as existing keys are one of the specified types. To iterate over the existing keys, we need to apply Generic Constrains using
This way, if we specify non-existing key, TypeScript will throw an error
We cannot call T[Key] if Key doesn't exist in T so we’re safe now ✅
Check out the solution in Playground ⭐️typescripteasy