Rest Parameters
Rest parameters in TypeScript allow functions to accept an indefinite number of arguments as an array. Think of them like a catch-all bucket for any extra arguments we might pass to a function. Instead of specifying every possible argument individually, we can use the rest parameter syntax, which is represented by three dots (…) followed by the name of the parameter. This lets you gather up any remaining arguments into an array, making your function more flexible and capable of handling varying numbers of inputs.
Syntax:
function functionName(param1: Type, ...restParams: Type[]) {
// Function body
}
Example: A function `sum` calculates the sum of multiple numbers, including a first number followed by an arbitrary number of additional numbers. The function is called with parameters `1, 2, 3, 4, 5`, resulting in the sum `15` logged to the console.
function sum(firstNumber: number, ...remainingNumbers: number[]) {
let total = firstNumber;
for (const num of remainingNumbers) {
total += num;
}
return total;
}
console.log(sum(1, 2, 3, 4, 5));
Output:
[LOG]: 15
What is Parameter Destructuring in TypeScript ?
Parameter destructuring in TypeScript is a way to extract values from objects or arrays passed as function parameters, making it easier to work with their properties or elements directly within the function body.
There are several methods through which parameter destructuring is achieved in TypeScript which are as follows:
Table of Content
- Object Destructuring
- Array Destructuring
- Rest Parameters
- Default Values