Recursion in Type Definitions
What you'll learn: How to write type definitions that reference themselves to handle nested structures of unlimited depth.
The Core Idea
Just like functions can call themselves in JavaScript, TypeScript types can reference themselves in their own definitions. This is type recursion, and it's essential when modeling data structures where you don't know how deep the nesting goes—think nested arrays, tree structures, or deeply nested objects.
Without recursion, you'd need a separate type for each level of nesting. With recursion, one type definition handles them all.
Understanding Type Recursion
Think of Russian nesting dolls: each doll contains another doll of the same shape, just smaller. You don't define "Doll1," "Doll2," "Doll3"—you define "Doll" as "a doll that may contain another Doll."
In TypeScript, recursive types follow the same principle:
type NestedArray<T> = T | NestedArray<T>[];
This reads as: "A NestedArray<T> is either a T, or an array of NestedArray<T>." The type references itself, allowing infinite nesting.
Real-World Example: JSON Values
Consider typing all possible JSON values:
type JSONValue =
| string
| number
| boolean
| null
| JSONValue[]
| { [key: string]: JSONValue };
The type calls itself in two places: arrays can contain JSONValue, and object properties can be JSONValue. This single definition handles JSON of any depth.
Why Recursion Matters
Without recursion, you'd write:
type Level1 = string | number;
type Level2 = Level1 | Level1[];
type Level3 = Level2 | Level2[];
// ... forever
That's unmaintainable and has a hard depth limit. Recursion solves this elegantly.
Key Takeaway: Recursive type definitions let you model infinitely nested structures with a single type that references itself, essential for trees, deeply nested objects, and any structure with arbitrary depth.