Sub topic 12
Base cases, depth limits and tail-recursive form
This chapter assumes you can write a recursive conditional type with infer, and that you have seen Split, Reverse and UnwrapPromise from earlier chapters. Here the question is why such types sometimes fail. You will see how recursion ends, where the compiler stops it, and how to rewrite a type so it can run much deeper.
Every recursive type needs a base case
A recursive conditional type has two kinds of branches. One branch calls the alias again with a smaller input. The other branch returns a result without calling it. That second branch is the base case.
In the types you have written so far, the base case comes from a failed pattern match:
UnwrapPromise<string>stops becausestringdoes not extendPromiseLike<infer U>.Split<'abc', '.'>stops because'abc'has no.to match.Reverse<[]>stops because[]does not match[infer Head, ...infer Rest].
In each case the input shrinks until the pattern can no longer match. The shrinking is what guarantees termination.
Termination can also depend on a counter. This type builds a tuple of a given length:
type BuildTuple<N extends number, Acc extends unknown[] = []> =
Acc['length'] extends N ? Acc : BuildTuple<N, [...Acc, unknown]>;
type Three = BuildTuple<3>; // [unknown, unknown, unknown]The base case is Acc['length'] extends N. The accumulator grows by one element per step, so its length eventually equals N.
Inputs that never reach the base case
A counter only terminates if the target is reachable. BuildTuple<-1> can never match, because a tuple length is never negative. The same is true of BuildTuple<1.5>. The compiler keeps expanding until it gives up with error TS2589, "Type instantiation is excessively deep and possibly infinite".
A guard in a wrapper type turns bad input into never before the recursion starts:
type BuildTuple<N extends number, Acc extends unknown[] = []> =
Acc['length'] extends N ? Acc : BuildTuple<N, [...Acc, unknown]>;
type Tuple<N extends number> =
`${N}` extends `-${string}` | `${string}.${string}` ? never : BuildTuple<N>;
type Ok = Tuple<3>; // [unknown, unknown, unknown]
type Neg = Tuple<-1>; // never
type Frac = Tuple<1.5>; // neverPutting the guard in a wrapper means it runs once, not at every step.
Where the compiler stops you
The compiler protects itself with several limits. The exact values have changed between versions, so treat the numbers below as orders of magnitude and check your own compiler version.
| Limit | Symptom | Typical cause |
|---|---|---|
| Instantiation depth for ordinary recursion, roughly 50 levels for a conditional type | TS2589, "excessively deep and possibly infinite" | Recursive call wrapped inside another type, input too large |
| Tail-recursion iteration cap, 1000 iterations (TypeScript 4.5 and later) | TS2589 | Tail-recursive type with an input needing more than 1000 steps |
| Tuple size, around 10,000 elements | TS2799, tuple type too large to represent | Counter or accumulator tuples that grow too much |
| Total instantiation count | TS2589 | A type that fans out into many branches, such as one recursing over each member of a large union |
The first row is the one you will meet most often. Here is a recursive type whose call is wrapped in a tuple spread:
type Repeat<T, N extends number, Acc extends unknown[] = []> =
Acc['length'] extends N ? [] : [T, ...Repeat<T, N, [...Acc, unknown]>];
type Five = Repeat<'x', 5>; // ['x', 'x', 'x', 'x', 'x']
// Repeat<'x', 200> fails with TS2589 on typical compiler versions.Each level has to wait for the level below it to finish before it can build its own tuple. The compiler must keep every pending level in memory, so the depth limit applies.
Tail-recursive form
TypeScript 4.5 added tail-recursion elimination for conditional types. If the recursive call is the entire result of a branch, nothing is left to do after it returns. The compiler can then loop instead of nesting, and it allows up to 1000 iterations.
The rule is simple. In a branch, the alias must call itself directly, with nothing wrapped around the call. These wrappers break it:
- A tuple or spread:
[Head, ...Self<Tail>] - A template literal: `
${Head}${Self<Tail>}` - An indexed access:
Self<Tail>[0] - An intersection or union:
Self<Tail> & X
Nested conditional types are fine, as long as every route ends in a direct call or a plain result.
The rewrite moves the work that was wrapped around the call into an extra parameter, called an accumulator. The accumulator carries the partial result forward, and the base case returns it.
type RepeatTail<
T,
N extends number,
Count extends unknown[] = [],
Out extends unknown[] = []
> = Count['length'] extends N
? Out
: RepeatTail<T, N, [...Count, unknown], [...Out, T]>;
type Many = RepeatTail<'x', 500>['length']; // 500Compare it with the earlier version. The spread [...Out, T] now sits inside an argument, not around the call, so the recursive call is the whole branch. The base case returns Out, the finished result.
Rewriting Split
Split from the earlier chapter wraps its call in [Head, ...Split<Tail, D>], so it hits the ordinary depth limit on long strings. The accumulator version avoids this:
type SplitTail<
S extends string,
D extends string,
Acc extends string[] = []
> = S extends `${infer Head}${D}${infer Tail}`
? SplitTail<Tail, D, [...Acc, Head]>
: [...Acc, S];
type Parts = SplitTail<'a.b.c', '.'>; // ['a', 'b', 'c']The base case, the branch where no delimiter remains, returns [...Acc, S]. That branch is not a recursive call, so it does not need to be a direct call.
Reverse from the previous chapter already had this shape. Its accumulator is the reason it can handle long tuples.
What tail recursion does not fix
A tail-recursive type has a higher ceiling. It does not have an unlimited one, and several problems remain.
- The 1000-iteration cap.
BuildTuple<2000>fails even in tail form. Processing two or more elements per step, for example matching[infer A, infer B, ...infer Rest], roughly halves the iteration count. - Tuple size. An accumulator that passes about 10,000 elements triggers TS2799 even when the iteration count is low.
- Compile time. A deep type can be slow even when it stays under every limit. Editors recompute it on each keystroke in the files that use it, so a type that takes a second to check hurts everyone.
- Recursion hidden in the argument.
Flatten<[...A, ...B]>is a direct call, but it can still require expensive work to compute the spread.
Recursive mapped types such as DeepReadonly are not tail-recursive, because the recursive call sits inside a property type. They are usually safe because their depth follows the nesting of your data, which is small. They can misbehave on generated types with very deep or self-referential structure. A depth counter makes the cutoff explicit:
type DeepReadonlyTo<T, Depth extends unknown[] = []> =
Depth['length'] extends 5
? T
: T extends (...args: any[]) => any
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonlyTo<T[K], [...Depth, unknown]> }
: T;
type Config = { a: { b: { c: { d: { e: { f: string } } } } } };
type Frozen = DeepReadonlyTo<Config>;
// Levels a through e are readonly. The value at depth 5 is returned unchanged.Here the base case is a depth limit you chose, not a failed pattern match. Types beyond the cutoff stay as they were, which is a deliberate and predictable loss of precision.
Testing the limits
Use the Equal and Expect helpers from the testing chapter to pin down both the behavior and the ceiling of your types. Add a test for a long input, so a later edit that breaks tail form fails right away:
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 SplitTail<
S extends string,
D extends string,
Acc extends string[] = []
> = S extends `${infer Head}${D}${infer Tail}`
? SplitTail<Tail, D, [...Acc, Head]>
: [...Acc, S];
type _Short = Expect<Equal<SplitTail<'a.b.c', '.'>, ['a', 'b', 'c']>>;
type _Single = Expect<Equal<SplitTail<'abc', '.'>, ['abc']>>;
type _Empty = Expect<Equal<SplitTail<'', '.'>, ['']>>;The empty-string and no-delimiter cases check the base case directly. When a limit matters to callers, you can also record the failure with // @ts-expect-error on a line that should exceed it, so a compiler upgrade that raises the limit shows up as an unused directive.
Summary of the rules
- Identify the base case before writing the recursive branch, and confirm every input can reach it.
- Put guards for invalid input in a wrapper type, not inside the recursion.
- Keep the recursive call as the whole branch, and carry partial results in accumulator parameters.
- Expect a ceiling of about 1000 iterations in tail form and a few dozen levels otherwise.
- Add tests for long inputs and edge inputs.
Exercise
This type is meant to join a tuple of strings with a delimiter, but it fails with TS2589 on tuples of about 60 elements. Explain why, and describe how to rewrite it.
type Join<T extends string[], D extends string> =
T extends [infer H extends string, ...infer R extends string[]]
? R extends [] ? H : ${H}${D}${Join<R, D>}
: '';
Show answer
The recursive call is wrapped inside a template literal, so the compiler cannot eliminate the tail call. Every level stays pending until the one below finishes, and the ordinary depth limit of roughly 50 levels applies. To rewrite it, add an accumulator string parameter, for example Acc extends string = ''. In the matching branch, call Join<R, D, ${Acc}${D}${H}> directly, and return Acc when the tuple is empty. Handle the first element so the delimiter is not added at the start, for example by starting from the first element and joining the rest.
Exercise
What does BuildTuple<-1> do when BuildTuple has the base case Acc['length'] extends N and no guard? Where would you put a fix?
Show answer
The accumulator length goes 0, 1, 2, and so on, and never equals -1, so the base case is never reached. The compiler recurses until it reports TS2589. The fix belongs in a wrapper type that checks the input once, for example Tuple<N> = ${N} extends -${string} ? never : BuildTuple<N>, so the recursion never starts for invalid input.
Exercise
A tail-recursive type processes one element per step and fails on a 1500-element tuple. Name two ways to get it to work.
Show answer
One way is to process several elements per step, for example by matching [infer A, infer B, infer C, ...infer Rest], which cuts the iteration count below the 1000 cap. Another way is to split the input into smaller chunks and combine the partial results. In both cases, keep the accumulator under the tuple size limit of about 10,000 elements.