Rest parameters in TypeScript and JavaScript allow you to define functions that can accept a variable number of arguments as an array. This is useful when you want to work with functions that can take different numbers of arguments without explicitly specifying them in the function signature. Rest parameters are denoted by the ellipsis (...
) followed by a parameter name, and they gather all the remaining arguments into an array.
function sum(…numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(5, 10, 15, 20)); // Output: 50
In this example, the sum
function uses a rest parameter named numbers
. This allows the function to accept any number of arguments, which are then gathered into an array called numbers
. The reduce
function is used to sum up all the numbers in the array.
- Syntax: The rest parameter is denoted by the ellipsis (
...
) followed by the parameter name (...numbers
in the example above). It must be the last parameter in the function parameter list. - Array: The rest parameter collects all additional arguments into an array.
- Type Annotation: You can add a type annotation to the rest parameter to specify the type of elements in the array. In the example,
...numbers: number[]
indicates that the elements in the array should be of typenumber
. - No Need to Specify Count: With rest parameters, you don’t need to specify the count of arguments when calling the function. You can provide as many arguments as you want.
- Empty Array: If you call the function without passing any arguments, the rest parameter will be an empty array.
- Using Other Parameters: Rest parameters can be used alongside other parameters in the same function.