Use a rest parameter when a function needs to accept more arguments than its named parameters account for. Prefix the final parameter with `...`: `function calculateTax(amount, discount = 0, ...extraFees)`. Extra arguments are collected automatically into `extraFees`; callers pass them normally, separated by commas. section 8.2.2
The main rules are:
- A function can have only one rest parameter, and it must be last. Its value is always an array, including an empty array when no extra arguments are passed. section 8.2.2
- In TypeScript, annotate the collected values as an array: `...extraFees: number[]`. A rest parameter permits extra arguments; an optional or default parameter instead permits an argument to be omitted. section 8.2.2
Add variable extra fees
In `src/index.ts`, `function calculateTax(amount: number, discount: number = 0, ...extraFees: number[]) { return (amount * 1.2) - discount + extraFees.reduce((total, fee) => total + fee, 0); }` accepts any number of fees. `calculateTax(100, 10, 20)` returns `130`; adding `1, 30, 7` returns `168`. The `0` gives `reduce` a starting total when the fees array is empty. section 8.2.2
Collecting arguments does not make their values safe to add. In JavaScript, reducing a rest array with `+` can concatenate a string instead of producing a numeric sum. Convert values to numbers and handle `NaN` when mixed inputs are possible. section 3.3.3
The same `...` spelling also appears in object operations, but its job depends on where it appears. In `let { price, ...someProperties } = hat`, object rest assigns the properties other than `price` to `someProperties`; it does not collect function arguments. Object spread, as in `{ ...hat, discounted: true }`, places properties into a new object. section 3.5.2
Listing 8.11 Applying parameter type annotations in the index.ts file in the src folder
function calculateTax(amount: number,
discount: number = 0, ...extraFees: number[]) {
return (amount * 1.2) - discount
+ extraFees.reduce((total, val) => total + val, 0);
}
let taxValue = calculateTax(100, 0);
console.log(`2 args: ${taxValue}`);
taxValue = calculateTax(100);
console.log(`1 arg: ${taxValue}`);
taxValue = calculateTax(100, 10, 20);
console.log(`3 args: ${taxValue}`);
taxValue = calculateTax(100, 10, 20, 1, 30, 7);
console.log(`6 args: ${taxValue}`);
The complete `src/index.ts` listing shows a typed rest parameter alongside a default parameter and calls with different numbers of fees. section 8.2.2


