๐ŸŽ“ A1Learner
๐Ÿ”

TypeScript Rest Parameters

A rest parameter gathers extra arguments into one array. The function then works through the items of that array.

Gather numbers into an array

The rest parameter collects each call argument into the scores array. A loop adds the items up.

function sum(...scores: number[]): number {
  let total: number = 0;
  for (const score of scores) {
    total = total + score;
  }
  return total;
}
console.log(sum(4, 5, 6));
console.log(sum(10, 20));

A named parameter before the rest

The label takes the first argument. Every later argument lands in the marks array.

function grade(label: string, ...marks: number[]): void {
  let total: number = 0;
  for (const mark of marks) {
    total = total + mark;
  }
  console.log(label + ": " + marks.length + " marks, total " + total);
}
grade("Quiz", 8, 9, 7);

Example

function average(...values: number[]): number {
  let total: number = 0;
  for (const value of values) {
    total = total + value;
  }
  return total / values.length;
}
console.log(average(10, 20, 30, 40));

Key points

  • Three dots before the parameter name mark a rest parameter.
  • A rest parameter is the last parameter in the list.
  • The rest parameter collects every remaining argument into an array.
  • The type written for a rest parameter is an array type.
  • A named parameter can stand before a rest parameter.
  • A call may pass no extra arguments at all, and the array is then empty.

In this example, the rest parameter gathers the four arguments into the values array. The loop adds them to a total of 100. The function divides the total by the array length of 4. The average is 25.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

What does a rest parameter collect the extra arguments into?