Sub topic 7
Type aliases that refer to themselves
Assume you know TypeScript generics, unions, tuples, mapped types, and basic function signatures. This chapter focuses on recursive type aliases: aliases whose definition refers back to the alias itself.
What a recursive type alias is
A recursive type describes data that can contain more data of the same general shape. Common examples include trees, nested arrays, JSON values, and linked lists.
A recursive definition needs two parts:
- A recursive branch that refers to the alias again.
- A non-recursive branch that stops the recursion.
For example, a JSON value can be a primitive, an array of JSON values, or an object whose properties are JSON values:
type JsonPrimitive = string | number | boolean | null;
type JsonValue =
| JsonPrimitive
| readonly JsonValue[]
| { readonly [key: string]: JsonValue };
const settings: JsonValue = {
enabled: true,
tags: ["typescript", "types"],
display: {
theme: "dark",
fontSize: 14,
},
};JsonValue refers to itself in both the array and object branches. The primitive branch stops the nesting. Without a branch that eventually does not refer to JsonValue, the type would not describe a useful finite value.
| Part | Example | Purpose | Column | Column |
|---|---|---|---|---|
| Base branch | `string \ | number \ | null` | Ends the nesting |
| Recursive branch | `readonly JsonValue[]` | Allows more nested values | ||
| Object branch | `{ [key: string]: JsonValue }` | Allows nested properties |
Visualizing the structure
A recursive alias describes a pattern that can repeat at any depth:
The type does not create an infinite runtime object. It describes the allowed shape of values, and each actual value has a finite depth.
Recursive aliases for tree structures
A tree node contains a value and child nodes. A leaf is a node whose children array is empty.
type TreeNode<T> = {
value: T;
children: TreeNode<T>[];
};
const files: TreeNode<string> = {
value: "src",
children: [
{
value: "index.ts",
children: [],
},
{
value: "types",
children: [
{
value: "config.ts",
children: [],
},
],
},
],
};
function countNodes<T>(node: TreeNode<T>): number {
return 1 + node.children.reduce((total, child) => {
return total + countNodes(child);
}, 0);
}
console.log(countNodes(files)); // 4TreeNode<T> keeps the value type generic while fixing the recursive structure. A TreeNode<number> has numbers at every node, while a TreeNode<string> has strings at every node.
Recursive aliases and recursion boundaries
TypeScript accepts many recursive aliases, but each recursive type should have a clear conceptual boundary. Ask these questions when designing one:
- What is the smallest valid value?
- Which branch repeats the type?
- Can a consumer create a finite value?
- Does the type preserve useful information at every level?
A recursive alias can also combine several recursive branches:
type NestedList<T> = T | readonly NestedList<T>[];
const values: NestedList<number> = [1, [2, [3, 4]], 5];Here, T is the base case and the array is the recursive case. The alias supports arbitrary nesting while keeping every leaf as a number.
Compile-time checking
The compiler checks each recursive level when you assign a value. This assignment fails because "large" is not a number:
type NestedNumber = number | readonly NestedNumber[];
const valid: NestedNumber = [1, [2, 3]];
// const invalid: NestedNumber = [1, ["large"]];Recursive aliases are therefore useful for modeling input and output contracts before writing recursive runtime code.
Exercise
What are the two essential parts of a useful recursive type alias?
Show answer
It needs a recursive branch that refers to the alias again and a base branch that eventually stops the recursion.