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
- Recursive Type Definitions
- Typing Tree Structures
- JSON Value Types
- Recursion Depth and Limits