Recursive Constraints for Tree Structures
What you'll learn: How to use generic constraints that reference themselves to safely type self-referential data structures like trees and linked lists.
Why Recursive Constraints Matter
Many real-world data structures are self-referential—they contain properties that point to more instances of the same type. Trees and linked lists are classic examples. Without recursive constraints, you lose type information as you traverse these structures, forcing you to use any or awkward type assertions.
Recursive constraints let you preserve type information at every level of nesting while maintaining flexibility through generics.
The Core Pattern
The key technique is defining a type parameter that extends a shape containing the same type parameter:
interface TreeNode<T extends TreeNode<T>> {
value: number;
children: T[];
}
This says: "Whatever T is, it must be a TreeNode containing more instances of itself."
A Concrete Tree Example
interface TreeNode<T extends TreeNode<T>> {
value: number;
children: T[];
}
interface BinaryNode extends TreeNode<BinaryNode> {
value: number;
children: [BinaryNode?, BinaryNode?]; // max two children
}
function sumTree<T extends TreeNode<T>>(node: T): number {
let sum = node.value;
for (const child of node.children) {
sum += sumTree(child); // TypeScript knows child is also T
}
return sum;
}
Notice how sumTree can traverse the tree recursively while TypeScript maintains that each child satisfies the same constraint as the parent.
Linked List Pattern
interface ListNode<T extends ListNode<T>> {
value: string;
next: T | null;
}
function findEnd<T extends ListNode<T>>(node: T): T {
return node.next === null ? node : findEnd(node.next);
}
The recursive constraint ensures node.next is also typed as T, enabling safe traversal.
Key Takeaway: Recursive constraints with extends let you type self-referential structures by having a generic type parameter constrain itself, preserving type safety through arbitrary nesting levels.