Syntax
interface TreeNode { label: string; children: TreeNode[]; }Examples
Recursive Types for Tree Data: working example
Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints 4.
interface TreeNode { label: string; children: TreeNode[]; }
function countNodes(node: TreeNode): number {
return 1 + node.children.reduce((sum, child) => sum + countNodes(child), 0);
}
const tree: TreeNode = {
label: "root",
children: [
{ label: "left", children: [] },
{ label: "right", children: [{ label: "leaf", children: [] }] }
]
};
console.log(countNodes(tree));- Expected result: The program prints 4.
- An empty children array is the traversal’s base case.
- Each node contributes one plus the counts of its child subtrees.
Best practices
- Use an iterative traversal for potentially very deep data.
- Validate external graphs and handle cycles if they are allowed.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook