Sub topic 11
Recursing over Tuples: Reverse and Accumulators
This chapter assumes you can write generic type aliases and read conditional types with infer. It also assumes you know tuple types, rest elements in tuples ([A, ...B[]]), and mapped types. Earlier chapters covered recursive conditional types, such as unwrapping nested Promises. This chapter applies the same idea to tuples, where one step handles one element.
Why tuples are the natural loop
A tuple is a fixed-length array type, such as [1, 2, 3]. TypeScript has no for loop at the type level, so you process a tuple by splitting off its first element, handling it, and calling the type again on the rest. Two features make this possible:
- Pattern matching with
infer:T extends [infer Head, ...infer Rest]captures the first element and the remaining elements as a new tuple. - Variadic spreads:
[...A, ...B]builds a new tuple by splicing two tuples together, and a spread can sit anywhere in the tuple.
The two building blocks look like this:
type Head<T extends unknown[]> = T extends [infer H, ...unknown[]] ? H : never;
type Tail<T extends unknown[]> = T extends [unknown, ...infer R] ? R : [];
type H1 = Head<[1, 2, 3]>; // 1
type T1 = Tail<[1, 2, 3]>; // [2, 3]
type T2 = Tail<[]>; // []The pattern [infer H, ...infer R] only matches a tuple with at least one element. An empty tuple fails the check, and that failure is the base case of most tuple recursion.
A first Reverse: recursion without an accumulator
The most direct way to reverse a tuple is to reverse the rest, then put the head at the end:
type ReverseNaive<T extends unknown[]> =
T extends [infer Head, ...infer Rest]
? [...ReverseNaive<Rest>, Head]
: [];
type R = ReverseNaive<[1, 2, 3]>; // [3, 2, 1]This works, and it reads like a mathematical definition. The recursive call sits inside a tuple, and TypeScript can only finish building that tuple after the inner call returns. For each element, the compiler keeps one more pending instantiation open. That matters once the tuple gets long, as the section on limits below explains.
The accumulator pattern
An accumulator is an extra type parameter that carries the result built so far. You give it a default, usually the empty tuple, so callers do not have to pass it.
type Reverse<T extends unknown[], Acc extends unknown[] = []> =
T extends [infer Head, ...infer Rest]
? Reverse<Rest, [Head, ...Acc]>
: Acc;
type Rev = Reverse<[1, 2, 3]>; // [3, 2, 1]Each step moves one element from the input to the front of the accumulator. Because each new head goes in front, the first element ends up last. When the input is empty, the accumulator is the answer, so the base case just returns Acc.
| Step | `T` | `Head` | `Rest` | `Acc` for the next call |
|---|---|---|---|---|
| 1 | `[1, 2, 3]` | `1` | `[2, 3]` | `[1]` |
| 2 | `[2, 3]` | `2` | `[3]` | `[2, 1]` |
| 3 | `[3]` | `3` | `[]` | `[3, 2, 1]` |
| 4 | `[]` | none | none | returns `[3, 2, 1]` |
The recursive call Reverse<Rest, [Head, ...Acc]> is the entire result of its branch. Nothing wraps it. That is the form the compiler can run as a loop, which the limits section covers.
Other uses of the same pattern
The structure is always the same: match head and rest, update the accumulator, recurse, and return the accumulator when the input is empty.
Transforming every element
This type wraps each element in a Promise:
type Promisify<T extends unknown[], Acc extends unknown[] = []> =
T extends [infer Head, ...infer Rest]
? Promisify<Rest, [...Acc, Promise<Head>]>
: Acc;
type P = Promisify<[string, number]>; // [Promise<string>, Promise<number>]Here the new element goes at the end ([...Acc, ...]), so the order is kept. Reverse puts it at the front ([Head, ...Acc]), so the order flips. That one position is the only difference between a copy and a reversal.
Filtering elements
The accumulator can also skip elements:
type Filter<T extends unknown[], U, Acc extends unknown[] = []> =
T extends [infer Head, ...infer Rest]
? Filter<Rest, U, [Head] extends [U] ? [...Acc, Head] : Acc>
: Acc;
type Strings = Filter<[1, 'a', 2, 'b'], string>; // ['a', 'b']The check is written [Head] extends [U] instead of Head extends U. Wrapping both sides in a one-element tuple turns off distribution. If an element is itself a union such as string | number, the unwrapped form would split it and could produce a union of tuples. The wrapped form tests the whole element at once.
Counting with a tuple
Type-level code cannot add numbers, but a tuple's length is a number literal. Growing a tuple one element at a time acts as a counter:
type TupleOf<N extends number, Acc extends unknown[] = []> =
Acc['length'] extends N
? Acc
: TupleOf<N, [...Acc, unknown]>;
type Three = TupleOf<3>; // [unknown, unknown, unknown]
type Len = TupleOf<3>['length']; // 3This one stops on a property of the accumulator instead of an empty input.
Mapped types for simple cases
If you only need to transform each element independently, a mapped type over a tuple is shorter and has no depth limit:
type PromisifyMapped<T extends unknown[]> = { [K in keyof T]: Promise<T[K]> };Use recursion when a step depends on the elements before it, or when the output has a different length or order than the input (reverse, filter, zip, take). Use a mapped type for a plain element-by-element transform.
Edge cases
- Empty tuple.
Reverse<[]>is[], because the pattern fails immediately andAccis still the default. - Plain arrays.
string[]does not match[infer Head, ...infer Rest], because an array might be empty and the pattern needs at least one element. SoReverse<string[]>is[], notstring[]. If you need to support arrays, add an explicit branch such asT extends readonly unknown[] ? (number extends T['length'] ? T : ...), or constrain the input to real tuples. - Readonly tuples. A
readonly [1, 2]is not assignable to the mutable pattern[infer H, ...infer R], so it falls to the base case and returns the empty accumulator. To accept both, constrain withreadonly unknown[]and matchreadonly [infer Head, ...infer Rest]. A mutable tuple is assignable to the readonly pattern. - Unions of tuples.
Tis a naked type parameter inT extends [...], so a union of tuples distributes.Reverse<[1, 2] | [3, 4]>gives[2, 1] | [4, 3]. - Optional elements. A tuple like
[1, 2?]does not match the required-element patterns in the way you might expect, so test such inputs before relying on them. - Labels. Labeled tuples such as
[name: string, age: number]keep their element types when you recurse, but the labels are lost in the rebuilt tuple.
Here is a version of Reverse that accepts readonly input:
type ReverseR<T extends readonly unknown[], Acc extends unknown[] = []> =
T extends readonly [infer Head, ...infer Rest]
? ReverseR<Rest, [Head, ...Acc]>
: Acc;
type RR = ReverseR<readonly ['a', 'b']>; // ['b', 'a']Depth limits and tail recursion
TypeScript caps how deeply types can instantiate each other. When a recursion goes too deep, the compiler reports error 2589, "Type instantiation is excessively deep and possibly infinite."
The cap depends on the shape of the recursion:
- Non-tail recursion, such as
[...ReverseNaive<Rest>, Head], keeps each call pending until the inner one finishes. The limit is on the order of 100 nested instantiations, so a tuple of a few hundred elements fails. - Tail recursion applies when the recursive call is the whole result of a conditional type branch. Since TypeScript 4.5 the compiler runs such types as a loop and allows about 1,000 iterations.
The accumulator is what makes the tail form possible. The partial result moves into a parameter, so nothing is left to do after the call returns.
Things that stop a call from counting as a tail call:
- Wrapping the call in a tuple, a spread, a template literal, or another type, as in
[...Reverse<Rest>, Head]. - Putting the recursive call inside an indexed access, such as
Reverse<Rest>[0]. - Using a type other than a conditional type for the recursion. Tail elimination applies to conditional types.
Choosing a design
| Question | Prefer |
|---|---|
| Does each output element depend only on the matching input element? | A mapped type over the tuple |
| Does the output change order, length, or depend on earlier elements? | Recursion with an accumulator |
| Could inputs be long (hundreds of elements)? | The accumulator form, with the call as the whole branch result |
| Must inputs be readonly or array types? | Constrain with `readonly unknown[]` and add a branch for non-tuples |
| Are the elements themselves unions? | Wrap checks in `[X] extends [Y]` to avoid distribution |
Exercise
What are Reverse<[]> and Reverse<string[]>, using the accumulator version of Reverse from this chapter, and why?
Show answer
Both are []. For [], the pattern [infer Head, ...infer Rest] does not match, so the base case returns Acc, which is the default []. For string[], the array might be empty, so it is not assignable to a pattern that requires a first element. The pattern fails the same way and the type returns the default accumulator [].
Exercise
Write Last<T>, which returns the last element of a tuple, or never for an empty tuple. Then write Take<T, N> in words: how would you use an accumulator and the length trick to keep only the first N elements?
Show answer
type Last<T extends unknown[]> = T extends [...unknown[], infer L] ? L : never; This works because a spread can come first in a tuple pattern, so L is bound to the final element. For Take, add a parameter Acc that starts as []. At each step match [infer Head, ...infer Rest]. If Acc['length'] extends N, return Acc. Otherwise recurse with Rest and [...Acc, Head]. If the input becomes empty before the count is reached, return Acc.
Exercise
Change one thing in Reverse so that Reverse<[1, 2, 3]> returns [1, 2, 3] instead of [3, 2, 1]. What does this show about the accumulator's role?
Show answer
Change [Head, ...Acc] to [...Acc, Head]. The new element is then appended at the end instead of placed in front. This shows that the position where you add to the accumulator decides the output order, and that the accumulator holds the result being built.