How to use Recursive Template Literal Types In Typescript
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.
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"]
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