Tuple Manipulation
February 9, 20261 min readpart 05/20
Difficulty: Intermediate to Advanced. Prerequisites: Basic tuple types, generics, infer keyword.
Tuple manipulation involves transforming fixed-length array types with heterogeneous element types. TypeScript provides powerful tools including variadic tuple types, labeled elements, and rest elements. These capabilities enable type-safe function composition and are the foundation for type-level arithmetic.
Key concepts
- Variadic tuple types with spread syntax [...T]
- Extracting first, last, and rest elements using infer
- Concatenating and reversing tuples at the type level
- Named/labeled tuple elements for better IDE support
- Converting between tuples and unions
Example
// Extract elements
type Head<T extends any[]> = T extends [infer F, ...any[]] ? F : never;
type Tail<T extends any[]> = T extends [any, ...infer R] ? R : [];
type Last<T extends any[]> = T extends [...any[], infer L] ? L : never;
// Concatenate and reverse
type Concat<A extends any[], B extends any[]> = [...A, ...B];
type Reverse<T extends any[]> = T extends [infer F, ...infer R] ? [...Reverse<R>, F] : [];
// Usage
type Nums = [1, 2, 3, 4, 5];
type First = Head<Nums>; // 1
type Rest = Tail<Nums>; // [2, 3, 4, 5]
type Combined = Concat<[1, 2], [3, 4]>; // [1, 2, 3, 4]
type Reversed = Reverse<Nums>; // [5, 4, 3, 2, 1]
type Len = Nums['length']; // 5
// Labeled tuple elements
type Point = [x: number, y: number];
function distance(from: Point, to: Point): number {
return Math.hypot(to[0] - from[0], to[1] - from[1]);
}
// Tuple to Union
type TupleToUnion<T extends any[]> = T[number];
type Union = TupleToUnion<[1, 2, 3]>; // 1 | 2 | 3
// Real-world: Prisma unwraps a tuple of promises to type $transaction results
type UnwrapTuple<T extends readonly unknown[]> = {
[K in keyof T]: T[K] extends Promise<infer U> ? U : T[K]
};
// $transaction([userQuery, countQuery]) => [User[], number]Resources
- TypeScript 4.0 - Variadic Tuples: Feature introduction
- Type Challenges: Tuple manipulation practice
Practice
- Tuple Length (TypeHero, Easy)
- First of Array (TypeHero, Easy)
- Last of Array (TypeHero, Medium)
- Concat (TypeHero, Easy)
- Push (TypeHero, Easy)
- Unshift (TypeHero, Easy)
- First of Array (Type Challenges, Easy)
- Last of Array (Type Challenges, Medium)
- Pop (Type Challenges, Medium)
- Push (Type Challenges, Easy)
- Reverse (Type Challenges, Medium)
Hints
- Use variadic tuple types [...T] to spread and combine tuples.
- Remember T["length"] gives you the length of a tuple as a literal number type.