Open In App

How to Transform Union Type to Tuple Type in TypeScript ?

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, conversion from union type to tuple type consists of mapping each type in the union to a position in the tuple. This process consists of using mapped types or conditional types to perform the transformation.

The below methods can be implemented to accomplish this task.

Using Mapped Types

In this approach, we are using mapped types in TypeScript to transform a union type into a tuple type by iterating over each element in the union type and creating a tuple with the same elements.

Syntax:

type NewType = {
  [Property in ExistingType]: NewProperty;
};

Example: The below example uses Mapped Types to transform union type to tuple type in TypeScript.

JavaScript
type UnionType =
    string | number | string;
type TupleType<T> = {
    [K in keyof T]: T[K];
};
type res = TupleType<UnionType[]>;
const tArray: res =
    ["Anant", 13, "anant@example.com"];
console.log(tArray);

Output:

["Anant", 13, "anant@example.com"]

Using Recursive Conditional Types

In this approach, we are using recursive conditional types in TypeScript to transform a union type into a tuple type by recursively splitting the union elements using slashes (/) and constructing a tuple with the separated elements.

Syntax:

type RecursiveType<T> = T extends /* condition */ ? /* true branch */ : /* false branch */ ;

Example: The below example uses Recusive Conditional Types to transform union type to tuple type in typescript.

JavaScript
type UnionType = 'name/age/email';

type TupleType
    <T extends string,
        R extends string[] = []> =
    T extends `${infer F}/${infer U}`
    ? TupleType<U, [...R, F]>
    : T extends `${infer F}`
    ? [...R, F]
    : never;

type res = TupleType<UnionType>;

const tArr: res = 
    ["name", "age", "email"];
console.log(tArr);

Output:

["name", "age", "email"]

Using Recursive Template Literal Types

In this approach, we utilize recursive template literal types to transform a union type into a tuple type. This method recursively splits the union elements using slashes (‘/’) and constructs a tuple with the separated elements.

Example: In this example we defines a type UnionToTuple<U> to transform a string union U into a tuple type, splitting it at “/” delimiter. An example and usage are provided, printing the resulting tuple.

JavaScript
type UnionToTuple<U> = 
    U extends string ? (
        U extends `${infer Head}/${infer Tail}` ? [Head, ...UnionToTuple<Tail>] : [U]
    ) : never;

// Example
type UnionType = 'name/age/email';
type TupleType = UnionToTuple<UnionType>; // Result: ["name", "age", "email"]

// Usage
const tuple: TupleType = ["name", "age", "email"];
console.log(tuple); 

Output:

["name", "age", "email"]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads