Open In App

Explain about rest parameters and arguments in TypeScript

In this article, we will try to understand all the basic facts or details which are associated with Rest Parameters and Arguments in TypeScript.

Rest Parameters:



Syntax: Following is the rest parameter syntax provided in TypeScript.

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

Here these “…” (triple dots) represents the rest parameter syntax followed by name of the rest parameter followed by the type of that rest parameter (must be of Array data type).



Rest Arguments:

Syntax: Following is the syntax of using the Rest Arguments in TypeScript (explained using an example).

let array_1 : number[] = [1 , 2 , 3];
let array_2 : number[] = [5 , 6, 7];
array_1.push(array_2);

The following examples will help us in order to understand the above-illustrated facts in a more clear manner (in case you don’t know, these examples could only be runnable in your local PC if you have installed typescript in it, otherwise you may choose some online typescript compilers).

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




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:

90
-5

Example 2: 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("Hello ", "GeeksforGeeks ", "ABCD ", "Apple"));

Output:

Hello  GeeksforGeeks , ABCD , Apple!

Example 3: In this example, we will perform multiplication of all the numbers which are passed in a function as arguments.




let multiply = (a: number, ...numbers: number[]): number =>{
  return numbers.reduce((acc, curr) => acc * curr, a);
}
 
// Function call
let result1 = multiply(2, 2, 2, 2, 7);
let result2 = multiply(2, 3, 2, 5, 8);
 
// Printing data
console.log(result1);
console.log(result2);

Output:

112
480

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


Article Tags :