How to create recursive types
· Category: TypeScript
Short answer
Recursive types reference themselves within their definition. In TypeScript, you can create recursive interfaces and type aliases to model nested data structures.
Steps
- Define a tree node:
interface TreeNode { value: string; children: TreeNode[]; } - Define a linked list:
type LinkedList<T> = T & { next: LinkedList<T> } | null; - Model nested JSON:
type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue }; - Use
interfacefor object shapes to avoid circular alias limitations. - Test recursive types with sample data.
Tips
- Interfaces support recursion more naturally than type aliases in older TypeScript versions.
- Tail-recursion optimization on conditional types (TypeScript 4.5+) helps deep recursive instantiations.
Common issues
- Excessively deep recursion causes
Type instantiation is excessively deep and possibly infiniteerrors. - Recursive types with conditional logic may need careful base-case design.