How to create recursive types

· Category: TypeScript

Short answer

Recursive types reference themselves within their definition. In TypeScript, you can create recursive interfaces and type aliases to model nested data structures.

Steps

  1. Define a tree node: interface TreeNode { value: string; children: TreeNode[]; }
  2. Define a linked list: type LinkedList<T> = T & { next: LinkedList<T> } | null;
  3. Model nested JSON: type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue };
  4. Use interface for object shapes to avoid circular alias limitations.
  5. Test recursive types with sample data.

Tips

  • Interfaces support recursion more naturally than type aliases in older TypeScript versions.
  • Tail-recursion optimization on conditional types (TypeScript 4.5+) helps deep recursive instantiations.

Common issues

  • Excessively deep recursion causes Type instantiation is excessively deep and possibly infinite errors.
  • Recursive types with conditional logic may need careful base-case design.