Open In App

How to Derive Union Type From Tuple/Array Values in TypeScript ?

This article will show how to derive union type from tuple/array values in TypeScript language. The union type in TypeScript is mainly formed by combining multiple types. We will see various approaches through which we can derive union type.

Below are the possible approaches:

Using Mapped Type

In this approach, we are using Mapped Type to derive union type. We have defined the mapped type as tupleToUnion1 which converts a tuple type T into the union type of its elements. The unionFromTuple is a type that is derived from the tuple tupVal and an ex is the assigned valid value (Hello GFG) to the derived union type.

Syntax:

type TupleToUnion<T extends any[]> = T[number];

Example: Below is the implementation of the above-discussed approach.

type tupleToUnion1<T extends any[]> = T[number];
const tupVal: [string, number, boolean] = ['Hello GFG', 23, true];
type unionFromTuple = tupleToUnion1<typeof tupVal>;
const ex: unionFromTuple = 'Hello GFG';
console.log(ex);

Output:

"Hello GFG" 

Using Extract Utility Type

In this approach, we are using Extract Utility Type, where we have defined the tuple as tupVal and created a type as tupleToUnion2 by extracting a union type from its assignable values. Then we use the derived type to declare a variable myVar that can only be assigned values of the extracted union type.

Syntax:

type Extract<T, U> = T extends U ? T : never;

Example: Below is the implementation of the above-discussed approach.

const tupVal = ['Hello GFG', 23, true] as const;
type tupleToUnion2 = 
    Extract<typeof tupVal[number], string | number | boolean>;
const myVar: tupleToUnion2 = 23 ;
console.log(myVar);

Output:

23

Using Conditional Types with infer

In this approach, we utilize conditional types with the infer keyword to extract individual types from the tuple/array and then merge them into a union type.

Syntax:

type TupleToUnion3<T extends readonly any[]> = T extends readonly (infer U)[] ? U : never;

Example: This TypeScript snippet derives a union type from a tuple/array using conditional types with `infer`. It extracts the individual types from the tuple and forms a union.

type TupleToUnion3<T extends readonly any[]> =
    T extends readonly (infer U)[] ? U : never;

const tupVal = ['Hello GFG', 23, true] as const;
type UnionFromTuple2 = TupleToUnion3<typeof tupVal>;
const ex2: UnionFromTuple2 = true;
console.log(ex2);

Output:

true
Article Tags :