Recursive Type Aliases
You'll learn: How type aliases can reference themselves to model data structures that contain themselves, like trees or linked lists.
What Is a Recursive Type Alias?
A recursive type alias is a type that references its own name in its definition. Just like a function can call itself (recursion in programming), a type can contain itself as part of its structure.
Think of Russian nesting dolls: each doll contains a smaller version of itself, until you reach the smallest one. Recursive types work the same way — a value of this type can contain another value of the same type, nested inside.
Why You Need Recursive Types
Some data structures are naturally self-referential:
- Linked lists: Each node points to the next node (same type)
- Tree nodes: Each node has child nodes (same type)
- File systems: Folders contain files or more folders (same type)
- Comment threads: Comments can have reply comments (same type)
Without recursive types, you couldn't accurately model these structures.
Syntax Example
type LinkedListNode = {
value: number;
next: LinkedListNode | null;
};
type TreeNode = {
value: string;
children: TreeNode[];
};
type JSONValue =
| string
| number
| boolean
| null
| JSONValue[]
| { [key: string]: JSONValue };
Notice how LinkedListNode references itself in the next property, TreeNode contains an array of itself, and JSONValue can be an array or object containing more JSONValue types.
Key Takeaway: Recursive type aliases allow you to model infinite nesting structures by having a type reference itself, essential for trees, lists, and other self-similar data patterns.