Rest Parameters
π¨βπΌ Rest parameters let functions accept any number of arguments, collected into
an array. This is the opposite of spreadβinstead of expanding, we're collecting.
function sum(...numbers: Array<number>): number {
return numbers.reduce((a, b) => a + b, 0)
}
sum(1, 2) // 3
sum(1, 2, 3, 4, 5) // 15
The
.reduce() method shown above is covered later in Exercise 6. For now,
you can use a simple for loop instead:function sum(...numbers: Array<number>): number {
let total = 0
for (const n of numbers) {
total += n
}
return total
}
Rest vs Spread
The
... syntax means different things in different contexts:// SPREAD - expanding into individual elements
const arr = [1, 2, 3]
console.log(...arr) // 1 2 3 (expanded)
// REST - collecting into an array
function fn(...args: Array<number>) {
// args is an array of all passed numbers
}
Combining with Regular Parameters
Rest must be the last parameter:
function greetAll(greeting: string, ...names: Array<string>): string {
return names.map((name) => `${greeting}, ${name}!`).join(' ')
}
greetAll('Hello', 'Alice', 'Bob', 'Charlie')
// "Hello, Alice! Hello, Bob! Hello, Charlie!"
- Create a function using rest parameters to accept variable arguments
- Create a function with both regular and rest parameters
- Use rest in combination with spread to transform arguments
π° Rest parameter syntax:
function myFunc(...items: Array<string>): void {
// items is Array<string>
}