Sub topic 14
Variadic Tuple Types
This chapter assumes basic JavaScript arrays, TypeScript annotations, and union types. You should already know that a tuple stores values with a fixed length and a type for each position.
A variadic tuple type is a tuple type that can contain an unknown number of elements. The elements are represented by a generic tuple parameter and can be spread into another tuple. This lets a function preserve the exact length and types of its arguments.
Why ordinary arrays lose information
An array type such as unknown[] tells TypeScript that the collection can contain any number of values. It does not preserve the position-specific types.
function concatArrays(a: unknown[], b: unknown[]): unknown[] {
return [...a, ...b];
}
const left: [number, string] = [1, "one"];
const right: [boolean] = [true];
const result = concatArrays(left, right);
// unknown[]The runtime result is [1, "one", true], but its type is only unknown[]. TypeScript no longer knows that the first element is a number or that the third element is a boolean.
A variadic tuple keeps that information:
function concat<
T extends unknown[],
U extends unknown[]
>(a: T, b: U): [...T, ...U] {
return [...a, ...b];
}
const left: [number, string] = [1, "one"];
const right: [boolean] = [true];
const result = concat(left, right);
// [number, string, boolean]
const [count, label, enabled] = result;
console.log(count, label, enabled);Here, T captures the complete first tuple and U captures the complete second tuple. The return type [...T, ...U] joins them in order.
Generic functions with tuple parameter lists
A tuple can represent a function's complete parameter list. A generic constraint such as Args extends unknown[] means that Args must be a tuple or array type.
function callWith<Args extends unknown[], Return>(
fn: (...args: Args) => Return,
args: Args
): Return {
return fn(...args);
}
function formatUser(name: string, age: number): string {
return `${name} is ${age}`;
}
const message = callWith(formatUser, ["Ada", 36]);
// string
console.log(message);The compiler infers Args as [string, number]. It therefore rejects calls with the wrong number or types of arguments.
// callWith(formatUser, ["Ada"]); // Error: missing argument
// callWith(formatUser, [36, "Ada"]); // Error: wrong orderThis pattern is useful for wrappers, event dispatchers, middleware, and decorators. The wrapper can add behavior while retaining the original function's parameter list.
Adding parameters with tuple spreads
A variadic tuple can add elements before or after another tuple.
type WithRequestId<Args extends unknown[]> = [requestId: string, ...Args];
type UserArgs = [name: string, age: number];
type LoggedUserArgs = WithRequestId<UserArgs>;
// [requestId: string, name: string, age: number]You can also append a callback:
type WithCallback<Args extends unknown[], Result> =
[...Args, callback: (value: Result) => void];
type SaveArgs = WithCallback<[id: number, name: string], boolean>;
// [id: number, name: string, callback: (value: boolean) => void]The spread must represent an array or tuple type. A common error is trying to spread a non-array type:
// type Invalid = [...string]; // Error: string is not an array type| Type | Meaning |
|---|---|
| `unknown[]` | Any-length array; positions are not preserved |
| `[number, string]` | Exactly two positions with fixed types |
| `[...T, ...U]` | A tuple formed by joining two tuple types |
| `[prefix: string, ...Args]` | A required value followed by a generic tuple |
Practical limits and choices
Use a variadic tuple when the relationship between positions matters. It is a strong choice for forwarding function arguments or composing parameter lists.
Use an ordinary array when the values are homogeneous and the length does not carry useful meaning. A variadic tuple can become difficult to read when many generic spreads are nested.
Mutable tuple parameters use T extends unknown[]. If a function must also accept readonly tuples, use T extends readonly unknown[] and avoid mutating the tuple inside the function.
Exercise
What is the inferred type of concat([1, "a"] as [number, string], [false] as [boolean]) when concat returns [...T, ...U]?
Show answer
[number, string, boolean]. The first tuple contributes two positions and the second contributes one.