TypeScript Rest Arguments are that we pass in while merging two data types (suppose concatenation of two arrays) using the same “…” (triple dots). These types of arguments are generally used for merging or concatenation or for any other operational purpose.
Syntax:
function function_name(...rest: type[]) {
// Type of the is the type of the array.
}
Example 1: In this example, we will get the sum of arguments of integers that are passed in a function using the rest parameter syntax.
Javascript
function getSum(...numbers: number[]): number {
let sum = 0;
numbers.forEach((num) => sum += num);
return sum;
} // Function call console.log(getSum(10, 50, 30)); console.log(getSum(-50, 50, -10, 5)); |
Output:
Example 2: In this example, we will concatenate several strings which are passed inside the function as arguments.
Javascript
let generateGreeting = (
greeting: string,
...names: string[]
)
: string => {
return greeting + " " +
names.join( ", " ) + "!" ;
}
// Function call console.log( generateGreeting( "Hello " , "GeeksforGeeks " ,
"ABCD " , "Apple" )
); |
Output: