Not a long time ago I discovered type-challenges for myself. Today I’ll show not only the implementation of
Get, but also some common issues with the implementation, improvements and its usage in production.
As I said, there’s a repo on GitHub: type-challenges. The current challenge is located in the “hard” category.
Here we work only with objects (as the solution doesn’t require accessing arrays and tuples) and also we always can access object keys as they are defined in test cases.
So what should we start then from?
path.split('.'). In Typescript, we also need to get the keys from the path string.
Thankfully, since TypeScript 4.1, we have Template Literal types. We can infer the keys by removing dots.
We can use the
Path type to do so:
It looks very simple and short. However once we write tests, we understand what was missed, as seen in the Playground validation. We forgot the case with only one single key left. Let’s add it:
To try it out, we can have a look at the Playground with tests cases.
Reducing the object
After having the keys, we can finally call
keys.reduce. To do so, we use another type
GetWithArray so we already know that keys are a string tuple:
To explain it in more detail:
K extends [infer Key, ...infer Rest]checks that we have at least one element in a tuple
Key extends keyof Olets us use
O[Key]to move recursively to the next step
Let’s test it again on the Playground. We again forgot the last case with a tuple without elements. Let’s add it:
Let’s test it together to clarify everything’s working as expected: Playground
Great, we did it ✅