TypeScript Course
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?

Flash Cards

Question

Why did it require an interface?

Click to reveal answer
Answer

In older versions of TS, `type` aliases evaluated eagerly (instantly), causing infinite loops if they referenced themselves. Interfaces evaluate lazily. TS 3.7 fixed this, so now `type` aliases can be fully recursive.

Question

Excessively deep error?

Click to reveal answer
Answer

If your recursive type logic is extremely complex (e.g., recursive conditional mapped types), the TS compiler has a built-in safety limit (usually around 50 levels of recursion) to prevent the IDE from crashing. If it hits this limit, it throws this error.