DEV Community

Cover image for Advanced Typed Get
beraliv
beraliv

Posted on

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:

Get function 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:

Path transforms a string into keys, version 1

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:

Path transforms a string into keys, final version

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:

GetWithArray for objects, version 1

To explain it in more detail:

  1. K extends [infer Key, ...infer Rest] checks that we have at least one element in a tuple
  2. Key extends keyof O lets 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:

GetWithArray for objects, version 2

Final version with tests is available on Playground

All together

Get for type challenge

Let's test it together to clarify everything's working as expected: Playground

Great, we did it ✅


To read the full article, go to Advanced Typed Get | beraliv

It also includes:

  1. Optional paths
  2. Accessing arrays and tuples
  3. One solution
  4. Binding to JavaScript
  5. Summary

Top comments (0)