Sub topic 7
Type aliases that refer to themselves
This chapter assumes you can write generic type aliases, read union, intersection and tuple types, and use keyof in a mapped type. It covers how a type alias can mention its own name, which self-references the compiler accepts, and which ones fail. The later chapters on recursive conditional types and recursive mapped types rely on these rules.
Why types need to refer to themselves
Some data has no fixed depth. A JSON document can hold an array that holds an object that holds another array. A file tree has folders inside folders. A comment thread has replies to replies. You can't describe this shape by writing out a fixed number of levels, because the real data may go one level deeper than you wrote.
A recursive type alias solves this. The alias uses its own name in its definition, so one short definition covers every depth.
type Json =
| string
| number
| boolean
| null
| Json[]
| { [key: string]: Json };
const data: Json = {
name: "report",
tags: ["a", "b"],
nested: { ok: true, items: [1, 2, [3, 4, null]] },
};Json appears inside its own definition twice: as the element type of an array and as the value type of an object. Any value that is a string, number, boolean or null is valid at the bottom. Any array or object whose contents are also valid Json is valid above that.
Reading a recursive definition
Read a recursive alias like a recursive function. It needs at least one case that does not mention itself (the base case) and at least one case that does (the recursive case).
In Json, the base cases are string, number, boolean and null. The recursive cases are Json[] and { [key: string]: Json }. If an alias had only recursive cases, no finite value could satisfy it.
The same reading applies to a generic tree:
type Tree<T> = {
value: T;
children: Tree<T>[];
};
const tree: Tree<string> = {
value: "root",
children: [
{ value: "a", children: [] },
{ value: "b", children: [{ value: "b1", children: [] }] },
],
};
function countNodes<T>(node: Tree<T>): number {
return 1 + node.children.reduce((sum, child) => sum + countNodes(child), 0);
}
console.log(countNodes(tree)); // 4An empty children array is the base case. The type allows it because Tree<T>[] can have zero elements. The function that walks the type mirrors its structure, so it recurses on children and stops when the array is empty.
Writing a function over a recursive type
A recursive type works well with a recursive function. TypeScript narrows the union at each step, so you rarely need casts.
type Json =
| string
| number
| boolean
| null
| Json[]
| { [key: string]: Json };
function depth(value: Json): number {
if (Array.isArray(value)) {
return 1 + Math.max(0, ...value.map(depth));
}
if (value !== null && typeof value === "object") {
return 1 + Math.max(0, ...Object.values(value).map(depth));
}
return 0;
}
console.log(depth(1)); // 0
console.log(depth([1, [2]])); // 2
console.log(depth({ a: { b: [] } })); // 3After Array.isArray, value is Json[], so value.map(depth) type-checks because each element is a Json. After the typeof check, value is the object member, and Object.values(value) is Json[].
Which self-references the compiler accepts
Not every self-reference is allowed. The rule since TypeScript 3.7 is that the compiler may delay resolving a type name when it sits inside certain positions. In other positions it must resolve the name immediately, and a name that depends on itself cannot be resolved.
| Definition | Allowed | Why | Column |
|---|---|---|---|
| `type A = A \ | string` | No | The union is resolved eagerly, so `A` depends on itself with nothing in between. |
| `type A = A` | No | Nothing but itself. | |
| `type A = { next: A \ | null }` | Yes | An object property type is resolved later. |
| `type A = A[]` | Yes | The element type of an array is resolved later. | |
| `type A = Array<A>` | Yes | Type arguments of generic interfaces and classes are resolved later. | |
| `type A = [A, A]` | Yes | Tuple element types are resolved later. | |
| `type A<T> = T extends unknown[] ? A<T[number]> : T` | Yes | A conditional type's branches are resolved only when the condition is evaluated. |
The failing cases give error TS2456: "Type alias 'A' circularly references itself."
// Error TS2456: Type alias 'Bad' circularly references itself.
type Bad = Bad | string;The fix is to move the self-reference into a position that is deferred, which usually means putting it inside an object, array or tuple.
type NestedArray<T> = T | NestedArray<T>[];
const ok: NestedArray<number> = [1, [2, [3, [4]]]];
const alsoOk: NestedArray<number> = 5;Here the union T | NestedArray<T>[] is fine because the recursive part is the element type of an array. The bare T is the base case.
Interfaces and aliases
An interface has always been allowed to refer to itself, because its members are resolved lazily. Both of these declare the same shape:
interface TreeNodeI<T> {
value: T;
children: TreeNodeI<T>[];
}
type TreeNodeT<T> = {
value: T;
children: TreeNodeT<T>[];
};Pick between them for your usual reasons. A type alias is required when the recursive type is a union, such as Json, or a conditional type. An interface cannot be a union. Interfaces show their name in error messages, while aliases of object types sometimes display as expanded structure.
Recursion through a conditional type
A recursive alias does not have to describe a data shape. It can compute a type. A conditional type delays evaluation until its input is known, so it can refer to itself in the true or false branch.
type DeepElement<T> = T extends readonly (infer U)[] ? DeepElement<U> : T;
type A = DeepElement<number[][][]>; // number
type B = DeepElement<string>; // stringEvaluating DeepElement<number[][][]> goes like this:
number[][][]matchesreadonly (infer U)[]withU = number[][], so the result isDeepElement<number[][]>.- That matches with
U = number[], so the result isDeepElement<number[]>. - That matches with
U = number, so the result isDeepElement<number>. numberis not an array, so the false branch returnsnumber. This is the base case.
The false branch holds the base case here. Many recursive conditional types are built this way, with the pattern check as the recursive case and the fall-through as the end of recursion. The next chapters use this shape heavily.
Recursion that never ends
The compiler cannot prove that every recursive alias stops. If expanding a type produces a new, larger type each time, it never converges. The compiler counts the expansion depth and gives up with error TS2589: "Type instantiation is excessively deep and possibly infinite."
This is also the failure you get from a recursive conditional type that lacks a working base case. If the pattern in the extends clause matches every input, the false branch is never reached.
// Every T matches unknown, so the recursion never reaches a base case.
type NeverStops<T> = T extends unknown ? NeverStops<[T]> : never;Using NeverStops<string> triggers the depth error, because each step wraps the type in a new tuple and starts again.
Two habits prevent this:
- Write the base case first, then write the recursive case, and check that each recursive call gets a smaller or simpler input.
- Test the type with an input that should hit the base case immediately, such as
stringforDeepElement.
The limits on depth, and how to rewrite a type so it can recurse further, are covered in a later chapter.
Common errors
- A bare self-reference in a union.
type A = A | stringfails. Wrap the recursive part in an object, array or tuple. - No base case. A type like
type T = { child: T }is legal to declare, but no finite value can satisfy it. Add| null, an optional property or an empty array so a value can end. - Expecting cycles to type-check as data. A type can be recursive, but a value is a finite structure. If your data contains true cycles, such as a node pointing back to its parent, you need an explicit parent property typed as
Node | null, and you must build it with mutation. - Using an alias before checking that it terminates. Test the shallowest and deepest inputs you expect before relying on a recursive utility.
Exercise
Define a recursive type Comment for a discussion thread. Each comment has an author string, a text string and a list of replies, which are themselves comments. Then write countComments(c: Comment): number that counts a comment and all replies beneath it.
Show answer
type Comment = { author: string; text: string; replies: Comment[] };
function countComments(c: Comment): number {
return 1 + c.replies.reduce((sum, r) => sum + countComments(r), 0);
}
The replies: Comment[] property is allowed because object property types are resolved lazily. An empty replies array is the base case, so a comment with no replies counts as 1.
Exercise
Why does type Bad = Bad | string fail while type Ok = Ok[] | string is accepted?
Show answer
In Bad, the union is resolved eagerly and Bad is a direct member, so the alias depends on itself with no deferral and the compiler reports TS2456. In Ok, the self-reference is the element type of an array, a position the compiler resolves lazily, so the alias can be defined before its elements are examined.