Flatten Tuple Type in TypeScript

Example of Flatten use

Today we discuss Flatten

It works the same way as Array.prototype.flat when you pass Infinity

Let’s find out how to do that in TypeScript 💪

Iteration over tuple elements

Knowing the approach from different challenges, as we want to save the structure (it will be tuple at the end), we apply Type inference in conditional types with Rest elements in Tuples.

We iterate over elements:

Iterate over tuple elements

Then we have 2 cases:

  1. If the element is a tuple, we apply changes recursively
  2. Otherwise, we leave it as is

Let’s add second case:

Put element to the result tuple type

Call it recursively when needed

At the moment, if we have a look at Playground – https://tsplay.dev/w18bXW, we will find that not all tests are passed.

We forgot to apply function recursively when we have an element as tuple. Let’s have an example here:

Example where Flatten isn't working

In this case we cannot just add it to result tuple, we need to call Flatten before and then put all the elements of it to the result type. Let’s change the implementation based on that:

Solution

Now it’s working as expected 🔥

Check out Playground – https://tsplay.dev/WKk0DW

Thank you for your time and have a productive upcoming week 🚀

typescriptmedium

Let's chat and have fun 🧑‍💻👩‍💻

No more often than once a week I write 📄 about TypeScript 💪, video playback 📺 and frontend related topics. You can unsubscribe in any time ↘️