A rest parameter allows a function to accept an indefinite number of arguments as an array. It is denoted by the ‘…
’ syntax and indicates that the function can accept one or more arguments.
function add(...values: number[]) {
let sum = 0;
values.forEach(val => sum += val);
return sum;
}
const sum = add(5, 10, 15, 20);
console.log(sum); // 50
In contrast, the rest arguments allow a function caller to provide a variable number of arguments from an array. Consider the following example.
const first = [1, 2, 3];
const second = [4, 5, 6];
first.push(...second);
console.log(first); // [1, 2, 3, 4, 5, 6]