Recursion
Recursion is a function (or a type) that refers to itself. At runtime, a recursive function walks a value. At the type level, a recursive type describes that value, and a recursive conditional type transforms it.
Detailed Explanation
The runtime idea is the same as in JavaScript: a function calls itself on a smaller input, with a base case that does not call. TypeScript adds a type for the value you are walking, and it will not infer a useful type for a recursive function unless you annotate the return.
function depth(node: Tree): number {
return 1 + Math.max(0, ...node.children.map(depth));
}
Tree has to be written so that children is Tree[]. That is a recursive type. The function's return type should be annotated; inference often gives up on recursive functions and reports an error, or infers any in older settings.
Two layers people mix up:
Value recursion: the call stack grows with the input depth. Tail-call elimination is not guaranteed in JavaScript. Deep trees still overflow. Types do not change that.
Type recursion: type Json = ... | Json[] | { [k: string]: Json } describes unbounded nesting. The compiler expands this lazily. A recursive conditional type (type Walk<T> = T extends ... ? Walk<U> : T) expands at instantiation time and has a depth limit. "Type instantiation is excessively deep" is the type-level stack overflow.
When you type a recursive algorithm, write the recursive data type first (see recursive types), then write the function with an explicit return type. For trees, a discriminated union ({ kind: "leaf"; value: T } | { kind: "branch"; kids: Forest<T> }) makes the base case a switch the compiler can exhaust.
Generics on recursive functions (function walk<T>(node: Node<T>): T[]) keep the payload type. The recursion is on the structure, not on T. Do not try to recurse "until T is not a Promise" in a value function unless you also have a runtime test; Awaited<T> is a type, not a loop you can call.
Prefer an explicit stack when depth is unbounded. The type of the stack is Array<Frame>, and you avoid both the call-stack limit and the recursive-type expansion in the function's inference.
This page is not a tutorial on recursion as a problem-solving technique. It is about keeping the value-level function and the type-level description in agreement. The JavaScript recursion page covers the problem-solving part.
Code Examples
1. A recursive value type and a recursive function with an annotated return.
// 1. A recursive value type and a recursive function with an annotated return.
type Tree = { value: number; children: Tree[] };
function depth(node: Tree): number {
if (node.children.length === 0) return 1;
return 1 + Math.max(...node.children.map(depth));
}
const t: Tree = { value: 1, children: [{ value: 2, children: [] }] };
console.log(depth(t)); // 22. A generic walk that preserves the payload.
// 2. A generic walk that preserves the payload.
type Node<T> = { value: T; children: Node<T>[] };
function values<T>(node: Node<T>): T[] {
return [node.value, ...node.children.flatMap(values)];
}3. Prefer a stack when depth is unknown.
// 3. Prefer a stack when depth is unknown.
function depthIter(root: Tree): number {
const stack: Array<{ node: Tree; d: number }> = [{ node: root, d: 1 }];
let max = 1;
while (stack.length) {
const frame = stack.pop();
if (!frame) break;
max = Math.max(max, frame.d);
for (const child of frame.node.children) {
stack.push({ node: child, d: frame.d + 1 });
}
}
return max;
}Common Gotchas
Recursive functions often need an explicit return type
without it, the compiler may error with "implicitly has return type 'any'" or fail to infer.
Type-level recursion has a depth limit
a conditional type that unwraps a hundred nested wrappers will fail even if the runtime value is fine.
Tail calls are not a TypeScript feature
`target` and emit will not turn your recursive function into a loop.
A recursive type and a recursive function can disagree
if `children` is optional in the type and always present at runtime (or the reverse), the base case will be wrong. Keep them matched.