Rest Parameters in Functions
Type functions that accept any number of arguments.
Functions With Many Arguments
Rest parameters let a function accept any number of arguments, collected into a single array. TypeScript types that array, giving you safety even with variable-length calls.
Basic Rest Parameter
Prefix the last parameter with ... and give it an array type. Inside the function it behaves like a normal array.
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0)
}
console.log(sum(1, 2, 3, 4)) // 10All lessons in this course
- Rest Parameters in Functions
- Spread in Arrays and Objects
- Tuple Rest Elements
- Typing Variadic Functions