Type-Level Iteration Over Tuples
You'll learn: How to process tuple elements one at a time using recursive types with head/tail splitting patterns.
At the type level, we don't have for-loops or while-loops. Instead, we use recursion to iterate through tuple elements. The classic pattern is to split a tuple into its first element (the "head") and the remaining elements (the "tail"), process the head, then recursively call the type with the tail until we reach an empty tuple.
The Head/Tail Pattern
Think of a tuple like a line of people. To process everyone, you:
- Talk to the first person (head)
- Move to the rest of the line (tail)
- Repeat until the line is empty
In TypeScript types, we use infer to extract these parts:
type Head<T extends unknown[]> = T extends [infer First, ...infer Rest]
? First
: never;
type Tail<T extends unknown[]> = T extends [infer First, ...infer Rest]
? Rest
: never;
type Example = [1, 2, 3];
type ExampleHead = Head<Example>; // 1
type ExampleTail = Tail<Example>; // [2, 3]
Recursive Iteration Example
Here's a type that sums all numbers in a tuple by processing one element at a time:
type Sum<T extends number[], Acc extends number = 0> =
T extends [infer First extends number, ...infer Rest extends number[]]
? Sum<Rest, Add<Acc, First>> // Process head, recurse with tail
: Acc; // Base case: empty tuple, return accumulator
// Helper to add two number literals (simplified)
type Add<A extends number, B extends number> =
[...Array<A>, ...Array<B>]['length'] extends infer R extends number ? R : never;
type Result = Sum<[1, 2, 3]>; // 6
The pattern: match [head, ...tail], process the head, recurse with the tail, and stop when the tuple is empty.
Common Applications
Type-level tuple iteration appears when:
- Building tuple transformation utilities
- Validating tuple shapes element-by-element
- Accumulating results across tuple elements
- Flattening or restructuring tuple types
Key Takeaway: Type-level iteration uses the head/tail pattern with infer to recursively process tuple elements one at a time, with a base case for empty tuples.