Advanced Typed Get
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.
Basic implementation
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?
Getting keys
Imagine we solve the same challenge in JavaScript:
Before calling keys.reduce
, we need to get a list of all keys. In JavaScript we can call 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: