beraliv

Transform tuple type into a union in TypeScript

Example of TupleToUnion use
Example of TupleToUnion use

Today we discuss Tuple to Union

We already solved a similar challenge Making object out of tuple.

This one is useful when we need to extract elements type out of tuple.

Iteration over a tuple

As we discussed it in Making object out of tuple and Includes, we can use Indexed Access Types to get the type of tuple's elements:

Solution
Solution

Here we use extends any[] as Generic Constrain to be able to call T[number] without errors

All together in Playground with test cases

Have a wonderful day ☀️

typescript

Comments

Alexey Berezin profile image

Written by Alexey Berezin who loves London 🏴󠁧󠁢󠁥󠁮󠁧󠁿, players ⏯ and TypeScript 🦺 Follow me on Twitter