Codectionary / Developer documentation / TypeScript

Recursive Types for Tree Data

A recursive type refers to itself to model nested data such as a tree. Pair the data model with recursive traversal that has a clear base case. Static typing does not guarantee that a runtime structure is acyclic or shallow enough to fit the call stack.

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));
  1. Expected result: The program prints 4.
  2. An empty children array is the traversal’s base case.
  3. 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

Specifications & further reading