← Back to TypeScript Course | Chapter 3: Variables and Functions | Lesson 8 of 10

Rest Parameters

Rest parameters allow a function to accept any number of arguments and collect them into an array. They are written using three dots before the parameter name.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
function total(...amounts: number[]): number {
  return amounts.reduce((sum, n) => sum + n, 0);
}
console.log(total(10, 20, 30, 40));

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.