typescript / expert
Snippet
Type-Safe Tail-Call Recursive Tuple Inversion
This snippet demonstrates tail-call recursion optimization at the type level for reversing tuples. By leveraging variadic tuple elements with an accumulator parameter, TypeScript processes deep tuple operations cleanly without triggering premature compiler recursion depth errors.
snippet.ts
typescript
1
2
3
4
5
6
type ReverseTuple<T extends readonly unknown[], Acc extends readonly unknown[] = []> =T extends readonly [infer Head, ...infer Tail]? ReverseTuple<Tail, [Head, ...Acc]>: Acc;type Reversed = ReverseTuple<[number, string, boolean]>;
Breakdown
1
type ReverseTuple<T extends readonly unknown[], Acc extends readonly unknown[] = []> =
Declares a recursive conditional type accepting an input tuple T and an accumulator Acc.
2
T extends readonly [infer Head, ...infer Tail]
Destructures the input tuple into its head item and tail rest array using infer.
3
? ReverseTuple<Tail, [Head, ...Acc]>
Recursively invokes itself with remaining items, prepending the head to the accumulator.
4
: Acc;
Base case returns the accumulated reversed tuple when T becomes empty.
5
type Reversed = ReverseTuple<[number, string, boolean]>;
Evaluates to the inverted tuple type [boolean, string, number].