Rest parameters
Concept and syntax
A rest parameter collects remaining arguments into an array or tuple. Annotate ...values: number[] to accept any number of numeric arguments. A rest parameter must be last. Spread an array into a compatible rest call; a tuple rest can describe a more constrained sequence.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
function sum(...values:number[]){return values.reduce((a,b)=>a+b,0);}console.log(sum(),sum(2,3),sum(...[4,5]));Expected output:
0 5 9Common mistake
Intentionally invalid; compile separately and do not execute.
function sum(...values:number[]){return values.length;}sum(1,"2");Expected diagnostic: TS2345. All collected arguments must be numbers. Supply a numeric value.
Practice and recap
Add an initial required multiplier before the rest parameter.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Rest parameters — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function sum(...values:number[]){return values.reduce((a,b)=>a+b,0);}console.log(sum(),sum(2,3),sum(...[4,5]));Which diagnostic and explanation match the rejected example under the lesson settings?
function sum(...values:number[]){return values.length;}sum(1,"2");