0Pricing
TypeScript Academy · Lesson

Typing Tree Structures

Model nested tree nodes with recursive types.

A Tree Node Type

Trees generalize lists: each node has a value and an array of child nodes of the same type. This is a recursive type with a children array.

type TreeNode<T> = {
  value: T;
  children: TreeNode<T>[];
};
const leaf: TreeNode<number> = { value: 1, children: [] };
console.log(leaf.value);

Building a Small Tree

A node with children is just nested objects. The empty array is the natural base case for a leaf.

type TreeNode<T> = { value: T; children: TreeNode<T>[] };
const tree: TreeNode<string> = {
  value: "root",
  children: [
    { value: "a", children: [] },
    { value: "b", children: [] }
  ]
};
console.log(tree.children.length);

All lessons in this course

  1. Recursive Type Definitions
  2. Typing Tree Structures
  3. JSON Value Types
  4. Recursion Depth and Limits
← Back to TypeScript Academy