Sub topic 13
Tuples as function parameter lists
This chapter assumes you know tuple types, optional and rest elements in tuples, labeled elements, and generic functions with constraints like T extends unknown[]. It shows how a function's parameter list is itself a tuple type, and how to use that when you write wrappers, forwarders and argument helpers.
A parameter list is a tuple
TypeScript treats the parameters of a function as one tuple type. These two signatures describe the same function type:
type A = (host: string, port: number) => void;
type B = (...args: [host: string, port: number]) => void;Each parameter is one tuple element. Parameter names become the element labels, and an optional parameter becomes an optional element. A rest parameter becomes a rest element. This mapping works in both directions, so you can read a parameter list as a tuple and write a tuple where a parameter list is expected.
Reading a parameter list with Parameters
The built-in Parameters<F> utility type extracts the tuple from a function type. Pair it with typeof to read the parameters of an existing function.
function connect(host: string, port: number): void {
console.log(`${host}:${port}`);
}
type ConnectArgs = Parameters<typeof connect>; // [host: string, port: number]
const args: ConnectArgs = ["localhost", 8080];
connect(...args);Spreading args into the call works because ConnectArgs is a tuple. The compiler knows there are exactly two elements and checks each one against the matching parameter.
| Utility type | Result |
|---|---|
| `Parameters<F>` | Tuple of the parameters of function type `F` |
| `ConstructorParameters<C>` | Tuple of the parameters of constructor type `C` |
| `ReturnType<F>` | The return type of `F`, not a tuple |
Why spreading an array fails
A spread argument must have a tuple type, or it must be passed to a rest parameter. A plain array has an unknown length, so the compiler cannot match its elements to fixed parameters.
function add(a: number, b: number): number {
return a + b;
}
const nums = [1, 2]; // number[]
// add(...nums); // Error: A spread argument must either have a tuple type or be passed to a rest parameter.
const pair: [number, number] = [1, 2];
console.log(add(...pair)); // 3If you build an argument list in a variable first, annotate it as a tuple. You can also write it as [1, 2] as const, which gives readonly [1, 2]. A readonly tuple can be spread into a call as well.
function add(a: number, b: number): number {
return a + b;
}
const fixed = [1, 2] as const;
console.log(add(...fixed)); // 3Typing a rest parameter with a tuple
A rest parameter does not have to be T[]. You can give it a tuple type, and callers then pass the elements as ordinary arguments.
function log(
...args: [level: "info" | "warn", message: string, code?: number]
): void {
const [level, message, code] = args;
console.log(level, message, code ?? "-");
}
log("info", "started");
log("warn", "disk almost full", 507);
// log("info"); // Error: Expected 2-3 arguments, but got 1.The labels appear in editor tooltips as parameter names. The optional element code? makes the third argument optional. Inside the function, args is a tuple, so destructuring gives each variable its own type.
This is a useful alternative to a long list of positional parameters when the list is easier to describe as a tuple. It matters most with the next technique.
Parameter lists that depend on an earlier argument
A union of tuples as a rest parameter gives you overloads that are checked against each other. The first argument acts as a discriminant, and the rest of the arguments depend on it.
function emit(
...args: ["start"] | ["progress", percent: number] | ["error", cause: Error]
): void {
switch (args[0]) {
case "start":
console.log("started");
break;
case "progress":
console.log(`${args[1]}%`);
break;
case "error":
console.log(args[1].message);
break;
}
}
emit("start");
emit("progress", 40);
emit("error", new Error("disk full"));
// emit("progress"); // Error: no overload expects 1 argument for "progress"Checking args[0] narrows args to one member of the union, so args[1] has the right type in each branch. Compared with overload signatures, this form needs only one implementation signature, and the implementation is type-checked against the same declaration that callers see.
Forwarding arguments with a generic wrapper
The most common use of this feature is a wrapper that accepts any function and returns a function with the same parameters. A type parameter constrained to unknown[] captures the whole parameter tuple.
function connect(host: string, port: number): void {
console.log(`${host}:${port}`);
}
function withLogging<A extends unknown[], R>(
fn: (...args: A) => R,
): (...args: A) => R {
return (...args) => {
console.log("calling", fn.name, args);
return fn(...args);
};
}
const loggedConnect = withLogging(connect);
// loggedConnect: (host: string, port: number) => void
loggedConnect("localhost", 8080);
// loggedConnect("localhost"); // Error: Expected 2 arguments, but got 1.TypeScript infers A as [host: string, port: number], so the wrapper keeps the arity, the types, the labels and the optional markers of the original. The constraint is unknown[] rather than any[]. Inside the wrapper, args is a tuple type, so you can inspect it safely.
You can also use Parameters and ReturnType on a function-typed parameter, for example F extends (...args: any[]) => any. The A, R form is usually clearer, because the compiler infers the parts directly and you avoid a second lookup.
Splitting a parameter list
A function type can split its parameters into a head and a tail. The tail is a type parameter that captures all remaining parameters. This is the basis of partial application.
function connect(host: string, port: number): void {
console.log(`${host}:${port}`);
}
function bindFirst<H, T extends unknown[], R>(
fn: (head: H, ...tail: T) => R,
head: H,
): (...tail: T) => R {
return (...tail) => fn(head, ...tail);
}
const connectLocal = bindFirst(connect, "localhost");
// connectLocal: (port: number) => void
connectLocal(8080);Here H is inferred as string and T as [port: number]. The spread fn(head, ...tail) type-checks because T is constrained to an array type and the function's own signature uses the same split.
Variadic tuple types such as [...A, ...B] can describe a signature that joins two lists. They work well for building a type from known parts. Inferring A and B from a single [...A, ...B] is a different case, because the compiler has no rule for where the split falls. When you need to take a list apart, use the head and rest form shown above.
Gotchas
Parameters<F>returns a mutable tuple, even if the arguments should not change. Annotate your own variable asReadonly<Parameters<F>>if you want to prevent mutation.- For an overloaded function,
Parametersreads only the last overload signature. The other overloads are ignored. - For a generic function, type parameters are replaced by their constraints.
Parameters<typeof identity>for<T>(x: T) => Tis[x: unknown]. - A parameter with a default value is optional in the tuple.
function f(a: string, b = 1)gives[a: string, b?: number | undefined]. - A spread of an array type is allowed only into a rest parameter. Use a tuple type or
as constfor everything else.
Summary of the technique
- A parameter list is a tuple, and a tuple can be used as a rest parameter list.
Parameters<typeof fn>extracts the tuple, andfn(...tuple)calls with it.- A generic
A extends unknown[]in(...args: A) => Rcaptures any parameter list in a wrapper. - A union of tuples in a rest parameter gives checked, discriminated argument lists.
- A head and rest signature splits a list for partial application.
Exercise
Write a function delay with the signature delay<A extends unknown[]>(ms: number, fn: (...args: A) => void): (...args: A) => void. The returned function must call fn after ms milliseconds with the same arguments, and must keep the parameter types of fn. What type does delay(100, (id: number, label?: string) => {}) have?
Show answer
Implementation: function delay<A extends unknown[]>(ms: number, fn: (...args: A) => void): (...args: A) => void { return (...args) => { setTimeout(() => fn(...args), ms); }; }. The inferred result type is (id: number, label?: string | undefined) => void, because A is inferred as [id: number, label?: string | undefined].
Exercise
Given function resize(width: number, height: number): void {}, you write const dims = [800, 600]; resize(...dims);. Why does this fail, and give two different ways to fix it without changing resize.
Show answer
dims is inferred as number[], and a spread argument for fixed parameters needs a tuple type. Fix 1: annotate it, const dims: [number, number] = [800, 600];. Fix 2: use as const, const dims = [800, 600] as const;, which gives readonly [800, 600] and can be spread into the call.