Rest Parameters
Accept any number of arguments as a typed array.
Syntax
function sum(...nums: number[]) { }A rest parameter uses ... to gather all remaining arguments into an array. You type it as an array type.
This is perfect for functions like sum or a logger that accept a variable number of inputs.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- A logger function accepts any number of values to print, typed as a rest parameter of unknown[].
- A math utility sums an arbitrary count of numbers passed as a typed rest parameter.
- A tagged template helper collects variadic string segments through a rest parameter for safe concatenation.
More examples
Rest parameter typed as array
Collects any number of numeric arguments into a typed array, which is then reduced to a single total.
function sum(...numbers: number[]): number {
return numbers.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100Rest after required parameters
Combines a required first parameter with a typed rest to capture zero or more additional string arguments.
function tag(label: string, ...values: string[]): string {
return `[${label}] ${values.join(', ')}`;
}
tag('fruits', 'apple', 'banana', 'cherry');
// '[fruits] apple, banana, cherry'Spread array into rest function
Spreads a typed array into a rest-parameter function, showing how arrays and rest parameters interoperate.
function multiply(...factors: number[]): number {
return factors.reduce((acc, n) => acc * n, 1);
}
const nums: number[] = [2, 3, 4];
console.log(multiply(...nums)); // 24
Discussion