Recursive Types
Recursive Types — the core idea
A recursive type can describe trees and nested documents by referring to itself. Recursive data structures need a terminating case. Avoid unbounded recursion on untrusted input, because JavaScript still has a finite call stack.
What you’ll learn
- Explain recursive types with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: The type permits TreeNode[] inside a Node. At runtime count starts with one for the parent and recursively adds one for each leaf, giving three nodes.
Keep the boundary clear: Recursive types do not prevent cyclic object graphs. If cycles are possible, add a visited-set or depth limit to traversal.
See the idea as a flow
Run the complete TypeScript example
Save the code as recursive-types.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
type TreeNode = { label: string; children?: TreeNode[] };
function count(node: TreeNode): number {
return 1 + (node.children ?? []).reduce((sum, child) => sum + count(child), 0);
}
const tree: TreeNode = { label: "root", children: [{ label: "a" }, { label: "b" }] };
console.log(count(tree));Verified output
3Build: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable recursive-types.ts; run: node recursive-types.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
The type permits TreeNode[] inside a Node. At runtime count starts with one for the parent and recursively adds one for each leaf, giving three nodes.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
Recursive types do not prevent cyclic object graphs. If cycles are possible, add a visited-set or depth limit to traversal.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Add a grandchild under a and predict count(tree) before running it.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
A recursive type can describe trees and nested documents by referring to itself.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.