Rest Parameters
In this page:
Basic Rest Parameters
A rest parameter, written as ...args: number[], collects every remaining argument passed to a function into a single array. This lets a function accept an unlimited number of trailing arguments without listing each one individually.
Example: Basic Rest Parameters
function sum(...args: number[]): number {
return args.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4));
Rest Parameters with Required Parameters
A function can freely mix required parameters before a rest parameter, such as (first: string, ...rest: number[]). The required parameters are matched positionally first, and everything left over is gathered into the rest array.
Example: Rest Parameters with Required Parameters
function logScores(student: string, ...scores: number[]) {
console.log(student, scores);
}
logScores("Anya", 90, 85, 95);
Rest Parameters Are Arrays
Inside the function body, the rest parameter behaves exactly like a normal typed array, supporting every standard array method such as map, reduce, or forEach. There's no special syntax needed to work with it once it's been collected.
Example: Rest Parameters Are Arrays
function average(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0) / nums.length;
}
console.log(average(4, 8, 12));
Rest Parameters and Type Safety
Giving the rest parameter an appropriate array type, like ...values: string[], lets TypeScript check every single argument supplied through it against that type. Passing a mismatched value anywhere in that trailing group is caught at compile time.
Example: Rest Parameters and Type Safety
function joinWords(...values: string[]): string {
return values.join(" ");
}
// joinWords("a", 2); // rejected: 2 is not a string
console.log(joinWords("Hello", "World"));
When to Use Rest Parameters
Rest parameters are the right tool whenever the number of inputs a function accepts is naturally variable or simply unknown ahead of time, like a sum function that adds up any quantity of numbers. They replace the older arguments object with a properly typed alternative.
Example: When to Use Rest Parameters
function total(...amounts: number[]): number {
return amounts.reduce((sum, n) => sum + n, 0);
}
console.log(total(10, 20, 30, 40));
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: