typescript / intermediate
Snippet
Self-Referencing Generic Interfaces for Recursive Tree Structures
TypeScript interfaces can recursively reference themselves to model hierarchical data structures like trees or graph nodes while maintaining static type parameters throughout all child levels.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface TreeNode<T> {value: T;children?: TreeNode<T>[];}function countTreeNodes<T>(node: TreeNode<T>): number {let total = 1;if (node.children) {for (const child of node.children) {total += countTreeNodes(child);}}return total;}const root: TreeNode<string> = {value: "root",children: [{ value: "leaf1" }, { value: "leaf2" }]};
Breakdown
1
interface TreeNode<T> { ... children?: TreeNode<T>[]; }
Defines a generic interface holding a value of type T and optional array of child nodes of the same type.
2
function countTreeNodes<T>(node: TreeNode<T>): number {
Implements a recursive traversal algorithm that processes nodes matching the recursive generic schema.
3
const root: TreeNode<string> = { ... };
Instantiates a nested tree structure with string payloads and validated child array bounds.