Skip to content

Recursive Type

In one line

Recursive types reference themselves — useful for trees, JSON, nested menus, and fractal data structures.

In simple words

A recursive type is a type that references itself in its own definition. This lets you describe arbitrarily deep nested structures.

Common examples:

  • JSON — type JSON = string | number | boolean | null | JSON[] | { [key: string]: JSON }
  • Tree — type Tree<T> = { value: T; children: Tree<T>[] }
  • Linked list — type ListNode<T> = { value: T; next: ListNode<T> | null }

TypeScript handles recursive types well, but very deep nesting can hit recursion limits. Use them for naturally recursive data structures.

Example

typescript
// JSON type
type JSON = string | number | boolean | null | JSON[] | { [key: string]: JSON };

// Tree structure
type TreeNode<T> = {
  value: T;
  children: TreeNode<T>[];
};

const tree: TreeNode<string> = {
  value: "root",
  children: [
    { value: "a", children: [] },
    { value: "b", children: [{ value: "c", children: [] }] },
  ],
};

TreeNode<T> references itself for children. JSON references itself for arrays and objects. This enables arbitrarily deep nesting.

Common confusions

  • Confused with: generic type

    The difference: A generic type parameterizes over another type (List<T>). A recursive type references itself (Tree<T> = { children: Tree<T>[] }). A type can be both recursive and generic — TreeNode<T> is both: generic over T and recursive over itself.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary