Course contentsShow
← TypeScript
Lesson 1467 of 1,79633. Inference Inversion PatternsFree lesson

Type-Level Accumulators

Building up results across recursive calls using tuple spreading or mapped types.

Type-Level Accumulators

What you'll learn: How to build up results incrementally across recursive type operations using techniques like tuple spreading and accumulator parameters.

The Core Concept

In type-level programming, an accumulator is a type parameter that collects results as you recurse through a structure. Just like a loop accumulator in runtime code starts at zero and builds up a value, a type-level accumulator starts with an initial type (often an empty tuple [] or empty object {}) and progressively adds elements during recursive calls.

Think of it like building a snowball rolling down a hill: you start with a small core and add layers with each rotation until you reach the bottom.

Why Accumulators Matter

Without accumulators, recursive types often need to combine results at the end, which can hit complexity limits or produce inefficient types. Accumulators let you build as you go, carrying forward partial results through each recursive step.

Basic Pattern: Tuple Accumulator

The most common pattern uses tuple spreading to accumulate elements:

// Without accumulator - rebuilding at each level
type ReverseWrong<T extends unknown[]> = 
  T extends [infer First, ...infer Rest]
    ? [...ReverseWrong<Rest>, First]  // ❌ Rebuilds from scratch
    : [];

// With accumulator - building progressively
type Reverse<
  T extends unknown[],
  Acc extends unknown[] = []  // Accumulator starts empty
> = T extends [infer First, ...infer Rest]
  ? Reverse<Rest, [First, ...Acc]>  // ✅ Prepend to accumulator
  : Acc;  // Return accumulated result

type Test = Reverse<[1, 2, 3]>;  // [3, 2, 1]

How It Works

  1. Initialize: The accumulator parameter defaults to an empty state
  2. Recurse: Each iteration adds to the accumulator and passes the updated version forward
  3. Terminate: The base case returns the fully-built accumulator

Mapped Type Accumulation

You can also accumulate using mapped types for object transformations:

type Merge<
  T extends Record<string, unknown>,
  U extends Record<string, unknown>,
  Result extends Record<string, unknown> = {}
> = [keyof T] extends [never]
  ? Result & U
  : T extends Record<infer K, infer V>
    ? Merge<Omit<T, K & string>, U, Result & Record<K & string, V>>
    : never;

Key Takeaway: Type-level accumulators let you build results incrementally across recursive calls, making complex transformations more efficient and avoiding depth limits by carrying state forward rather than reconstructing it at each step.