Reversing Tuple Types
You'll learn how to build a type-level utility that takes a tuple type and returns a new tuple with its elements in reverse order.
Why Reverse Tuples at the Type Level?
Sometimes you need to transform tuple types—perhaps for API transformations, data pipelines, or advanced type manipulations. Reversing a tuple type means taking something like [string, number, boolean] and producing [boolean, number, string]. This happens entirely at compile time, giving you type safety for reversed data structures.
The Core Pattern: Recursive Tuple Reversal
Since TypeScript doesn't have built-in reverse for tuple types, you build it yourself using recursive conditional types with infer. The strategy:
- Extract the first element from the tuple
- Recursively reverse the remaining elements
- Append the first element to the end
- Base case: empty tuple returns empty tuple
Here's the implementation:
type Reverse<T extends readonly unknown[]> =
T extends readonly [infer First, ...infer Rest]
? [...Reverse<Rest>, First]
: T;
// Test it out
type Original = [1, 2, 3, 4];
type Reversed = Reverse<Original>; // [4, 3, 2, 1]
type StrNumBool = [string, number, boolean];
type Flipped = Reverse<StrNumBool>; // [boolean, number, string]
type Empty = Reverse<[]>; // []
type Single = Reverse<[42]>; // [42]
The magic happens in the conditional: [infer First, ...infer Rest] splits the tuple into its head and tail. Then [...Reverse<Rest>, First] recursively reverses the tail and appends the head at the end.
Real-World Usage
This pattern appears when transforming function parameter orders or mapping data structures:
// Reversing labeled tuple elements
type Coords = [x: number, y: number, z: number];
type ReversedCoords = Reverse<Coords>; // [z: number, y: number, x: number]
// Works with readonly tuples too
type ReadonlyTriple = readonly [1, 2, 3];
type ReversedReadonly = Reverse<ReadonlyTriple>; // readonly [3, 2, 1]
Key Takeaway: Reversing tuple types uses recursive conditional types with infer to destructure the tuple, reverse the tail recursively, and append the head to the end—enabling compile-time tuple transformations for type-safe data manipulation.