TypeScript Reference ยท Literal and Object Types
TypeScript rest parameters
Reference for TypeScript rest parameters: typing ...args as arrays or tuples, variadic generics, spreading arguments and rest elements in the middle of a tuple.
A rest parameter collects all remaining arguments into an array: function sum(...nums: number[]). Its type must be an array type or a tuple type. Because the rest parameter can be a tuple, TypeScript can describe functions whose argument list has a precise shape, and generic code can forward or transform argument lists with full type safety.
There can be only one rest parameter, and it must be the last in the list.
function sum(...nums: number[]): number { return nums.reduce((a, b) => a + b, 0); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
function f(...args: T[]): R; // array function g(...args: [A, B?, ...C[]]): R; // tuple, optional, nested rest function h<A extends unknown[]>(...args: A): R; // generic rest type Fn = (first: string, ...rest: number[]) => void;
| Part | Description |
|---|---|
...name |
Collects remaining arguments; required to be last. |
| Type | readonly arrays and tuples are allowed; mutable array types are the usual choice. |
| Generic form | A type parameter constrained to unknown[] captures a whole argument list as a tuple. |
Edge cases: a tuple rest type can contain optional elements and labeled elements; labels become the parameter names shown in editor hints. With noUncheckedIndexedAccess, reading args[0] from an array rest type gives T | undefined, but destructuring a tuple does not.
Usage notes
- Spread calls: spreading an array of unknown length into fixed parameters is an error; spread a tuple, or an array into a rest parameter.
- At runtime: rest parameters are real arrays (unlike the legacy
argumentsobject), so array methods are available. - Compatibility:
(...args: any[]) => voidaccepts any function type, which is why it appears in utility type constraints. Prefernever[]for parameters in constraints where you only want to accept (not call) functions. - Variadic tuple types:
[...A, ...B]concatenates tuples at the type level, enabling typedconcat,curryandpipehelpers. - Performance: passing very large arrays through spread calls can overflow the engine's argument limit.
- Overload alternative: if different arities mean different things, use overloads.