Sub topic 14
Variadic tuple types
A variadic tuple type is a tuple type that contains a spread of another type, such as [...T, ...U], where T and U are generic. The compiler fills in the spread when it knows what T and U are. Before TypeScript 4.0, you could not express "these parameters, then those parameters" or "this tuple with one more element" without long lists of overloads. Variadic tuples replace those overloads with one signature.
This chapter assumes you know generics with extends constraints, the Parameters utility type, rest parameters, and how tuples differ from arrays (including optional and rest elements). It also assumes you have seen conditional types with infer.
Spreading in a tuple type
In a value, [...a, ...b] copies the elements of a and b into a new array. A tuple type can do the same thing.
type Concat<A extends unknown[], B extends unknown[]> = [...A, ...B];
type R1 = Concat<[number, string], [boolean]>; // [number, string, boolean]
type R2 = Concat<[], [string]>; // [string]
const r: R1 = [1, "a", true];
console.log(r);The constraint extends unknown[] is required. Without it, the compiler reports "A rest element type must be an array type", because it cannot be sure the spread type is something it can expand.
The same spread can also appear in a fixed position:
type Prepend<T extends unknown[], V> = [V, ...T];
type Append<T extends unknown[], V> = [...T, V];
type P = Prepend<[number, string], boolean>; // [boolean, number, string]
type A = Append<[number, string], boolean>; // [number, string, boolean]These two types are the tuple equivalents of unshift and push. They return a new type, so no value is mutated.
What happens when the spread is not a tuple
T extends unknown[] also accepts ordinary arrays, such as number[], whose length is unknown. The result then keeps the array part as a rest element.
| `T` | `U` | `[...T, ...U]` |
|---|---|---|
| `[number]` | `[string]` | `[number, string]` |
| `[number]` | `string[]` | `[number, ...string[]]` |
| `number[]` | `[string]` | `[...number[], string]` |
| `number[]` | `number[]` | `number[]` |
The last row shows the normalization rule. A tuple can hold only one rest element, so two array spreads merge into a single array. If the element types differ, such as number[] and string[], the result is an array of the union of both element types, (string | number)[].
The third row is valid because TypeScript 4.2 allows a rest element in the middle or at the start of a tuple, as long as it is the only one. You can write [...string[], number] directly.
type Log = [...string[], number];
const ok1: Log = [3];
const ok2: Log = ["a", "b", 3];
// const bad: Log = ["a", "b"]; // Error: the last element must be a number.Writing a function with variadic tuples
The concat function below returns the exact tuple type of its two arguments. The parameters use [...T] and [...U] so that the compiler infers tuples from array literals instead of arrays.
function concat<T extends unknown[], U extends unknown[]>(
a: [...T],
b: [...U],
): [...T, ...U] {
return [...a, ...b];
}
const c = concat([1, "a"], [true]); // [number, string, boolean]
const [n, s, flag] = c;
console.log(n, s, flag);Without the [...T] wrapper, a parameter declared as a: T infers T from the literal [1, "a"] as (string | number)[], and the position information is lost. The spec's earlier example avoids this by passing variables that already have tuple types. The [...T] form makes literals work too.
flowchart LRThe diagram below shows how the result type is built for this call.
Rest parameters infer tuples
A rest parameter whose type is a generic array always infers a tuple. This is the basis for typing wrappers that forward their arguments.
function call<T extends unknown[], R>(
fn: (...args: T) => R,
...args: T
): R {
return fn(...args);
}
function repeat(text: string, times: number): string {
return text.repeat(times);
}
console.log(call(repeat, "ab", 3)); // "ababab"
// call(repeat, "ab", "3"); // Error: string is not assignable to number.Here T is inferred as [text: string, times: number] from repeat, and the remaining arguments are checked against it. The call is fully type-checked, including the argument count.
Splitting parameters: partial application
Variadic tuples can also describe a function whose parameters are split in two. partial fixes the first few arguments and returns a function that takes the rest.
function partial<T extends unknown[], U extends unknown[], R>(
fn: (...args: [...T, ...U]) => R,
...head: T
): (...tail: U) => R {
return (...tail) => fn(...head, ...tail);
}
function greet(greeting: string, name: string, mark: string): string {
return `${greeting}, ${name}${mark}`;
}
const hello = partial(greet, "Hello");
// hello: (name: string, mark: string) => string
console.log(hello("Ada", "!")); // "Hello, Ada!"The compiler infers T from the arguments you pass after fn, then gives U whatever parameters of fn are left over. The returned function carries the remaining parameter names and types.
Inspecting tuples with infer
Variadic positions also work inside conditional types, where infer can capture parts of a tuple.
type Head<T extends unknown[]> = T extends [infer H, ...unknown[]] ? H : never;
type Tail<T extends unknown[]> = T extends [unknown, ...infer Rest] ? Rest : [];
type Last<T extends unknown[]> = T extends [...unknown[], infer L] ? L : never;
type H = Head<[string, number, boolean]>; // string
type T = Tail<[string, number, boolean]>; // [number, boolean]
type L = Last<[string, number, boolean]>; // boolean
type E = Last<[]>; // neverHead and Last return never for an empty tuple because neither pattern matches. Tail returns [] by choice, since dropping the first element of nothing leaves nothing.
Readonly tuples and as const
A constraint of unknown[] rejects readonly tuples, because a readonly array is not assignable to a mutable one. If you want to accept as const values, widen the constraint to readonly unknown[].
function concatAll<T extends readonly unknown[], U extends readonly unknown[]>(
a: T,
b: U,
): [...T, ...U] {
return [...a, ...b];
}
const x = concatAll([1, "a"] as const, [true] as const);
// x: [1, "a", true]The result is a mutable tuple, even though the inputs were readonly. A spread always produces a fresh, mutable tuple type. Because the inputs are as const, the element types are the literal types 1, "a" and true. If you want a readonly result, write the return type as readonly [...T, ...U].
Gotchas and common errors
- Missing constraint.
[...T]with an unconstrainedTgives "A rest element type must be an array type". Addextends unknown[]orextends readonly unknown[]. - Two rest elements.
[...string[], ...number[]]written literally is an error ("A rest element cannot follow another rest element"). It is only normalized when it comes from instantiating generics. - Optional after rest.
[...string[], number?]is an error. Optional elements must come before the rest element. - Arrays inferred instead of tuples. If a result shows
(string | number)[]where you expected a tuple, check that the parameter is[...T]or a rest parameter, or that the argument isas const. - Element access on generic tuples. Inside a generic function,
a[0]on a value of type[...T]is typed throughT[0], which may beundefinedor unknown. Handle the generic case withinferin a conditional type instead. - Deep recursion. A recursive type that peels one element at a time works for short tuples. For hundreds of elements, it can fail with "Type instantiation is excessively deep and possibly infinite".
- No runtime effect. Variadic tuple types vanish at compile time. The runtime code is ordinary spread syntax, so nothing checks lengths when the data comes from outside your program, such as parsed JSON.
When to use them
Use variadic tuples when a function's parameters or return type depend on the exact shape of other arguments: wrappers, bind-style helpers, middleware chains and argument forwarding. For a simple list of items of the same kind, a plain T[] is clearer, and a variadic tuple adds nothing.
Exercise
Write a generic type DropFirst<T> that removes the first element of any tuple type, so that DropFirst<[string, number, boolean]> is [number, boolean]. Then write a function withoutFirst that takes a tuple parameter and returns its elements after the first, typed with DropFirst.
Show answer
Use a conditional type with infer: type DropFirst<T extends unknown[]> = T extends [unknown, ...infer Rest] ? Rest : [];. The function is function withoutFirst<T extends unknown[]>(tuple: [...T]): DropFirst<T> { const [, ...rest] = tuple; return rest as DropFirst<T>; }. The cast is needed because the compiler cannot verify the conditional type for a generic T. Calling withoutFirst(["a", 1, true]) gives [number, boolean].
Exercise
Why does concat(a, b) with a: T infer (string | number)[] for the literal [1, "a"], and what change makes it infer [number, string]?
Show answer
With a parameter typed as a bare T extends unknown[], the compiler treats an array literal as an array and widens it to the union of its element types. Declaring the parameter as [...T] (or using a rest parameter of type T) tells the compiler to infer a tuple, so T becomes [number, string].