Tuple members to union

Learn how to convert tuple members to a union type in TypeScript

In this post, we will learn how to use index access to convert tuple members to a union type in TypeScript.

Runtime array access

Imagine you wanted to get the value of an array member in JavaScript/TypeScript - you could do so by using the desired items index.

const secondItem = [1, 2, 3][1];
//      ^? 2

Type level index access

At the type level, you can follow the same pattern to retrieve the type at a specific index.

Let’s create a type which will extract the type from index position 1 in the tuple and assign it to our Derived type.

type T = [number, string, Date, any, unknown];
type Derived = T[1];
//      ^? string

Type-level index access visualised

Looking at the animation, you can see how index access is handled at the type level - the same as in JavaScript but with types.

An visual explanation of index access at the type level

Accessing multiple indexes

What if we wanted to create a type that would extract the type from index position 0 and 1 in the tuple and assign it to our Derived type? For this we can provide a union of indexes that we want - this will give us back a union type consisting of the desired types.

type T = [number, string, Date, any, unknown];
type Derived = T[0 | 1];
//      ^? number | string

Accessing all indexes

Now here comes the magic…

Instead of providing a union of indexes to extract the types we want, we can pass in the number type. This will simultaneously extract the types from all indexes in the tuple, resulting in a union of all types in the tuple.

type T = [number, string, Date, any, unknown];
type Derived = T[number];
//      ^? number | string | Date | any | unknown