Open In App

TypeScript Rest Parameters and Arguments

TypeScript Rest Parameters allow functions to accept an indefinite number of arguments of the same type, collecting them into an array. Arguments refer to the actual values passed to a function when it’s invoked, while Rest Parameters provide a way to handle multiple arguments as an array within the function.

Rest Parameters

A rest parameter allows us to pass zero or any number of arguments of the specified type to a function. In the function definition where we specify function parameters rest of the parameters should always come at last or the typescript compiler will raise errors.



Syntax

function function_name (...rest_parameter_name : type[]) { }

Parameters

Example: In this example, we will get the sum of arguments of integers that are passed in a function using the rest parameter syntax.




function getSum(...numbers: number[]): number {
    return numbers.reduce((total, num) =>
        total + num, 0);
}
  
const result = getSum(10, 20, 30, 40, 50);
console.log(result);

Output:



150

Rest Arguments

Syntax

let generateGreeting = (greeting: string, ...names: string[]): string => {
    return greeting + " " + names.join(", ") + "!";
}

Example: In this example, we will concatenate several strings which are passed inside the function as arguments.




let generateGreeting = 
    (greeting: string, ...names: string[]): string => {
    return greeting + " " + names.join(", ") + "!";
}
  
// Function call
console.log(generateGreeting("GeeksforGeeks ",
                             "is a computer science portal "));

Output:

GeeksforGeeks  is a computer science portal !

Reference: https://www.typescriptlang.org/docs/handbook/2/functions.html#rest-parameters-and-arguments


Article Tags :