How to use Recursive Conditional Types In Typescript

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"]

How to Transform Union Type to Tuple Type in TypeScript ?

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.

Table of Content

  • Using Mapped Types
  • Using Recursive Conditional Types
  • Using Recursive Template Literal Types

Similar Reads

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....

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....

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....