What Are Variadic Tuples?
You'll learn: How TypeScript allows tuples to have variable-length sections using rest elements, enabling type-safe operations on tuples with dynamic sizes.
The Core Idea
In previous lessons, you saw rest elements in tuples—parts of a tuple that can accept zero or more elements of a certain type. Variadic tuples take this concept further: they're tuple types that include one or more rest elements, allowing you to express tuples whose length and structure can vary while still maintaining type safety.
Think of it like a recipe template: "Start with two eggs, then add any number of vegetables, then finish with cheese." The vegetable section is variable in length, but the structure (eggs → vegetables → cheese) remains predictable.
Why This Matters
Before variadic tuples, you couldn't easily type functions that manipulate tuples of different lengths while preserving their exact types. Variadic tuples let you:
- Concatenate tuples without losing type information
- Prepend or append elements to tuples generically
- Type function signatures that work with any tuple length
Basic Structure
type VariadicTuple = [string, ...number[], boolean];
// Valid examples:
const a: VariadicTuple = ["hello", true]; // zero numbers
const b: VariadicTuple = ["hello", 1, true]; // one number
const c: VariadicTuple = ["hello", 1, 2, 3, true]; // three numbers
The ...number[] is the variadic part—it can match zero or more number elements.
Generic Variadic Tuples
The real power emerges with generics:
type Prepend<T extends unknown[], Item> = [Item, ...T];
type Original = [number, string];
type WithPrefix = Prepend<Original, boolean>;
// Result: [boolean, number, string]
Here, ...T spreads whatever tuple type you pass in, maintaining its exact structure while adding an element at the front.
Key Takeaway: Variadic tuples use rest elements (...T[]) to define tuple types with variable-length sections, enabling generic, type-safe operations on tuples of any size while preserving exact type information throughout transformations.