Sub topic 12
Base Cases, Depth Limits and Tail-Recursive Form
This chapter assumes you know TypeScript generics, conditional types, mapped types, tuple types, and template literal types. You should also be comfortable reading a type alias that transforms another type.
Recursive type utilities repeatedly apply a rule to a smaller part of an input. Every useful recursive type needs two things:
- A recursive case that performs another step.
- A base case that stops recursion.
Without a reliable base case, the compiler cannot finish evaluating the type.
Designing a base case
Consider a type that unwraps nested Promise types:
type UnwrapPromise<T> =
T extends PromiseLike<infer U>
? UnwrapPromise<U>
: T;
type Result = UnwrapPromise<Promise<Promise<number>>>;
// numberThe first branch is recursive. If T is a promise, the type extracts its inner value and calls itself again.
The second branch is the base case. When T is no longer promise-like, the type returns T directly.
A base case should satisfy two requirements:
- It must match inputs that cannot be reduced further.
- It must return a useful result without calling the type again.
This type does not terminate:
type BrokenUnwrap<T> = T extends PromiseLike<infer U>
? BrokenUnwrap<U>
: BrokenUnwrap<T>;For a non-Promise such as string, the false branch calls BrokenUnwrap<string> again. TypeScript eventually reports an excessive instantiation error.
Recursion depth limits
TypeScript limits how much type computation it performs. This prevents a complicated type from consuming unlimited compiler resources. The exact limits depend on the TypeScript version and the shape of the type.
A type can fail even when its logic is mathematically correct:
| Symptom | Likely cause | Typical response |
|---|---|---|
| `Type instantiation is excessively deep and possibly infinite` | Too many recursive steps | Reduce the input or redesign the recursion |
| Slow editor suggestions | Large intermediate types | Simplify helpers and avoid repeated expansion |
| Unexpected widening | The compiler lost literal information | Preserve literal inputs with `as const` or constraints |
Nested objects, long tuples, and long strings are common sources of depth errors. Recursive mapped types can also expand many properties at every level, so their work grows faster than a simple linear walk.
Tail-recursive form
A recursive call is in tail position when the result of that call is returned directly. An accumulator stores the work already completed.
This reverse operation builds a new tuple after each recursive call:
type ReverseSlow<T extends unknown[]> =
T extends [infer Head, ...infer Rest]
? [...ReverseSlow<Rest>, Head]
: [];
type Small = ReverseSlow<[1, 2, 3]>;
// [3, 2, 1]The recursive result is nested inside another tuple. The compiler must retain all those pending tuple constructions.
An accumulator moves that construction into the recursive argument:
type Reverse<
T extends unknown[],
Acc extends unknown[] = []
> =
T extends [infer Head, ...infer Rest]
? Reverse<Rest, [Head, ...Acc]>
: Acc;
type Result = Reverse<[1, 2, 3, 4]>;
// [4, 3, 2, 1]The recursive call is now the final operation in the true branch. This tail-recursive shape can let TypeScript handle more steps efficiently, although it does not remove all compiler limits.
The same idea works for parsing strings:
type Split<
S extends string,
Delimiter extends string,
Acc extends string[] = []
> =
S extends `${infer Head}${Delimiter}${infer Tail}`
? Split<Tail, Delimiter, [...Acc, Head]>
: [...Acc, S];
type Parts = Split<"one.two.three", ".">;
// ["one", "two", "three"]The accumulator records each fragment. The input becomes smaller because Tail excludes the first fragment.
Practical limits and choices
Tail recursion is useful when the input can be processed one step at a time. It is less useful when each step must combine many independently computed results.
When a type still reaches the depth limit:
- Reduce the input size.
- Use a simpler public type.
- Split one large transformation into smaller stages.
- Preserve an accumulator instead of rebuilding output after recursion.
- Consider doing the transformation at runtime and using inferred types instead.
The compiler checks type-level programs, but it is not a general-purpose data-processing engine.
Exercise
Why does Reverse<[1, 2, 3]> with an accumulator have a clearer termination point than a recursive type whose every branch calls itself?
Show answer
The tuple eventually becomes [], which matches the base case and returns the accumulator. A type whose every branch calls itself never reaches a branch that returns without recursion.