In TypeScript, you can use rest parameters in functions to represent an indefinite number of arguments as an array. Rest parameters are denoted by three dots (...
) followed by the parameter name. Here's an example of how you can use rest parameters in TypeScript functions:
typescript// Example 1: Rest parameter with type annotation
function sumNumbers(...numbers: number[]): number {
return numbers.reduce((sum, num) => sum + num, 0);
}
const result1 = sumNumbers(1, 2, 3, 4, 5);
console.log(result1); // Output: 15
// Example 2: Rest parameter without type annotation
function concatenateStrings(...strings: string[]) {
return strings.join(' ');
}
const result2 = concatenateStrings('Hello', 'world', '!');
console.log(result2); // Output: Hello world !
In the first example (sumNumbers
), the rest parameter ...numbers
is annotated with the type number[]
, indicating that it accepts an array of numbers. The function then uses the reduce
method to sum up all the numbers in the array.
In the second example (concatenateStrings
), the rest parameter ...strings
does not have a type annotation, but TypeScript automatically infers it as string[]
based on the provided arguments. The function joins the strings with a space between them.
Rest parameters can be useful when you want to write functions that can handle a variable number of arguments, making your code more flexible and expressive.