TypeScript
/Advanced
Recursive Types
Definition
Types that reference themselves within their own definition. This allows you to accurately type deeply nested data structures of unknown depth.
Explain Like I'm New
Imagine a Russian Nesting Doll. To describe it, you say: 'It is a Wooden Doll that contains either nothing, OR another identical Russian Nesting Doll.' A recursive type is exactly that—it calls itself until it reaches a base case.
Real World Example
Typing a JSON object! A JSON object can contain strings, numbers, OR another JSON object, which can contain strings, numbers, OR another JSON object... to infinity.
Common Use Cases
- •JSON data structures
- •File system trees (Folders containing Folders)
- •Linked Lists
Interactive Example
// Defining a deeply nested folder structure type FileNode = { name: string; isFile: boolean; // The magic: referencing itself! children?: FileNode[]; }; const myFileSystem: FileNode = { name: "root", isFile: false, children: [ { name: "document.txt", isFile: true }, { name: "images", isFile: false, children: [ // Nesting forever... { name: "photo.png", isFile: true } ] } ] }; // Defining valid JSON: type JSONValue = string | number | boolean | null | JSONObject | JSONArray; interface JSONObject { [key: string]: JSONValue; } interface JSONArray extends Array<JSONValue> {}
Interview Questions
basic
- What is a recursive type?
intermediate
- Why did recursive types previously require an interface, but now work with type aliases?
advanced
- What is the 'Type instantiation is excessively deep' error?