Recursive Type Definitions
Write types that refer to themselves safely.
What Is a Recursive Type?
A recursive type is a type that refers to itself in its own definition. This lets you describe data structures of unbounded depth.
type LinkedList<T> = {
value: T;
next: LinkedList<T> | null;
};
// next is the same type again, ending at null.A Linked List Type
The classic example: each node holds a value and a next pointer to another node, or null to end the chain.
type LinkedList<T> = { value: T; next: LinkedList<T> | null };
const list: LinkedList<number> = {
value: 1,
next: { value: 2, next: null }
};
console.log(list.value, list.next?.value);All lessons in this course
- Recursive Type Definitions
- Typing Tree Structures
- JSON Value Types
- Recursion Depth and Limits