Sub topic 11
Recursing over tuples: Reverse and accumulators
Prerequisites and the tuple pattern
This chapter assumes you know TypeScript generics, conditional types, union and tuple types, and variadic tuple types. A tuple is an array type with a fixed number and order of elements. A variadic tuple spread, written as ...Rest, captures the remaining elements as another tuple.
Type-level recursion applies a type alias to a smaller part of its input. For tuple recursion, the usual steps are:
- Check whether the tuple has a first element.
- Capture that element and the remaining tuple.
- Process the captured element.
- Recurse with the remaining tuple.
- Stop when the tuple is empty.
A conditional type can match a tuple with this pattern:
type HeadAndRest<T extends unknown[]> =
T extends [infer Head, ...infer Rest]
? [Head, Rest]
: never;
type Result = HeadAndRest<['a', 'b', 'c']>;
// [ 'a', ['b', 'c'] ]The infer Head variable captures the first element. The ...infer Rest variable captures the remaining elements. When T is [], the pattern does not match, so the recursive process needs a separate empty-tuple branch.
Why an accumulator helps
To reverse a tuple, take its first element and place it at the front of a result tuple. That result tuple is an accumulator: a type parameter that stores work completed so far.
type Reverse<
T extends unknown[],
Acc extends unknown[] = []
> =
T extends [infer Head, ...infer Rest]
? Reverse<Rest, [Head, ...Acc]>
: Acc;
type Reversed = Reverse<[1, 2, 3]>;
// [3, 2, 1]The first call is Reverse<[1, 2, 3], []>. Each recursive call removes one element from T and adds it to Acc.
| Input tuple | Accumulator |
|---|---|
| `[1, 2, 3]` | `[]` |
| `[2, 3]` | `[1]` |
| `[3]` | `[2, 1]` |
| `[]` | `[3, 2, 1]` |
When the input becomes empty, the conditional type returns Acc. This is the base case. Without it, the alias would have no result for an empty tuple and could not terminate.
Reading the recursive definition
The recursive branch contains three distinct ideas:
T extends [infer Head, ...infer Rest]checks and decomposes the tuple.Reverse<Rest, [Head, ...Acc]>makes the input smaller and updates the accumulator.: Accreturns the accumulated answer when no elements remain.
This is often clearer than rebuilding the output after recursion. A non-accumulator version can append the first element after reversing the rest:
type ReverseAfter<T extends unknown[]> =
T extends [infer Head, ...infer Rest]
? [...ReverseAfter<Rest>, Head]
: [];
type SameResult = ReverseAfter<[1, 2, 3]>;
// [3, 2, 1]Both definitions produce the same result. The accumulator version puts the recursive call in the final position of its branch. This tail-recursive shape can help TypeScript handle larger inputs, although the compiler still has limits on type complexity and recursion depth.
Preserving readonly tuples
The earlier definition accepts mutable tuples. If you want to reverse a readonly tuple, use readonly unknown[] and a readonly pattern:
type ReverseReadonly<
T extends readonly unknown[],
Acc extends readonly unknown[] = []
> =
T extends readonly [infer Head, ...infer Rest]
? ReverseReadonly<Rest, readonly [Head, ...Acc]>
: Acc;
const values = ['a', 'b', 'c'] as const;
type Backward = ReverseReadonly<typeof values>;
// readonly ['c', 'b', 'a']The readonly modifier must be included in both the constraint and the matching pattern. Otherwise, a readonly tuple might not satisfy the expected mutable shape.
Visualizing the recursion
Testing the result
Type-level results do not produce runtime values, so ordinary runtime tests are not enough. A compile-time assertion can verify that the resulting type is exactly the expected tuple.
type Equal<X, Y> =
(<T>() => T extends X ? 1 : 2) extends
(<T>() => T extends Y ? 1 : 2)
? true
: false;
type Expect<T extends true> = T;
type _ReverseTest =
Expect<Equal<Reverse<[1, 2, 3]>, [3, 2, 1]>>;
type _EmptyTest =
Expect<Equal<Reverse<[]>, []>>;If either expected type is changed incorrectly, Expect receives false, and the TypeScript compiler reports an error.
Exercise
What does Reverse<['x', 'y', 'z']> return, and what is the base case in the definition?
Show answer
It returns ['z', 'y', 'x']. The base case is the branch where T no longer matches [infer Head, ...infer Rest]; it returns the accumulator.