0Pricing
TypeScript Academy · Lesson

Type-Level Recursion

Loop over types using recursive conditional types.

Recursion in Types

A conditional type may refer to itself. That gives the type language loops. Most type-level recursion walks a tuple one element at a time, peeling off the head and recursing on the tail.

type Length<T extends unknown[]> =
  T extends [unknown, ...infer Rest]
    ? Length<Rest>
    : 0;
// (this counts down to a base case)

The Base Case

Every recursion needs a stopping condition. For tuples it is usually the empty tuple. When the pattern [head, ...rest] no longer matches, you have hit the end and return a fixed result.

type IsEmpty<T extends unknown[]> =
  T extends [] ? true : false;

type A = IsEmpty<[]>;     // true
type B = IsEmpty<[1, 2]>; // false

All lessons in this course

  1. Types as a Computation Language
  2. Type-Level Conditionals
  3. Type-Level Recursion
  4. Distributive Conditional Types
← Back to TypeScript Academy