TypeScript – Rest Parameter


TypeScript – The Rest Parameter


”;


The Rest Parameter

In TypeScript, a rest parameter allows a function to accept a variable number of arguments and store them as an array. This is useful when you want to define a function that can handle a variable number of arguments.

The rest parameter allows you to collect remaining arguments into a single array. The name of the rest parameter becomes the variable that holds this array.

Rest Parameter Syntax

The rest parameter is written using ellipsis/ three dots (…) followed by a parameter name in the function declaration. We use the array type for the type annotation of the rest parameter.

function funcName(...rest: type[]): returnType{
   // function body;
}

Where,

  • funcName − It”s the name of our function.

  • …rest − it stores the multiple arguments to the array named rest.

  • type[] − it specifies the type of the arguments

A function can have any number of ordinary parameters along with the rest parameter.

A rest parameter must be last in the parameter list.

function funcName (...rest1: type[], param1: type){}
//Error : A rest parameter must be last in a parameter list.

There must be only a single rest parameter in the function definition.

function funcName (...rest1: type[], ...rest2: number[]){}
//Error: A rest parameter must be last in a parameter list.

Same as above function declaration, the function expression can also have a rest parameter.

let getSum = function(...rest: type[]){
   function body;
} 

Examples

Let”s understand the rest parameters with help of some examples in TypeScript.

Example: Variable Length Parameter List

Using the rest parameter, we can call the function with a varying number of arguments. The rest parameter can handle these varying number of arguments.

In the example below, we have defined a function named sum with a rest parameter …nums. The arguments are stored as elements of array nums. Each time we call the function with different number of arguments, nums stores the arguments. And we can perform any operation of array on nums.

function sum(...nums: number[]) {
    let totalSum = 0;
    for (let num of nums) {
        totalSum += num;
    }
    return totalSum;
}
console.log(sum(10, 20, 30, 40));
console.log(sum(10, 20));
console.log(sum());

On compiling, it will generate the following JavaScript code.

function sum(...nums) {
    let totalSum = 0;
    for (let num of nums) {
        totalSum += num;
    }
    return totalSum;
}
console.log(sum(10, 20, 30, 40));
console.log(sum(10, 20));
console.log(sum());

The output of the above example code is as follows −

100
30
0

Example: Accessing argument length

In this example, we define a function named getLen with rest parameter …theArgs. We use the length property of array to get the length or number of arguments.

function getLen(...theArgs:number[]) {
  console.log(theArgs.length);
}
getLen();
getLen(5);
getLen(5, 6, 7);

On compiling, it will generate the following JavaScript code.

function getLen(...theArgs) {
    console.log(theArgs.length);
}
getLen();
getLen(5);
getLen(5, 6, 7);

The output of the above example code is as follows −

0
1
3 

Rest Parameter & Spread Operator

We have discussed about the rest parameters. The spread operator denoted with three dots (…) same as the rest parameters but works differently.

A rest parameter is used to collect the remaining parameters as an array. The spread operator spreads out the elements of an array into individual elements.

A spread argument must either have a tuple type or be passed to a rest parameter.

Example: Array as spread arguments

In this example, we defined two arrays arr1 and arr2 with three elements each. We call push() method on arr1 passing …arr2 as an argument. This works as spread argument as it spreads out/ unpacks the elements of the arr2 into the individual elements.

const arr1: number[] = [10, 20, 30];
const arr2: number[] = [40, 50, 60];
arr1.push(...arr2);
console.log(arr1);

On compiling, it will generate the following JavaScript code.

const arr1 = [10, 20, 30];
const arr2 = [40, 50, 60];
arr1.push(...arr2);
console.log(arr1);

The output of the above code is as follows −

[10, 20, 30, 40, 50, 60]

Example: Finding max/min number

In the example below, we find the maximum number. We define a function named getMax with a parameter, …args: number[]. We call Math.max() method passing argument, …args. The three dots in the argument, …args, works as spread operator. It spreads/ unpacks the elements of the array args.

function getMax(...args:number[]){ // here ...args as rest parameter
    return Math.max(...args); // here ... works as spread operator
}
console.log(getMax(10,20,30,40));
console.log(getMax(10,20,30));

On compiling, it will generate the following JavaScript code.

function getMax(...args) {
    return Math.max(...args); // here ... works as spread operator
}
console.log(getMax(10, 20, 30, 40));
console.log(getMax(10, 20, 30));

The output of the above example code is as follows −

40
30

Example: Passing rest argument

The rest argument unpacks the argument into the individual elements.

In this example, we define a function named multiply that takes three parameters of number types and return their product. The return type of the function is also number. We call the function passing a rest argument (…numbers).

function multiply(a: number, b: number, c: number): number {
    return a * b * c;
}
let numbers: [number, number, number];
numbers = [2, 3, 4];
console.log(multiply(...numbers));

On compiling, it will generate the following JavaScript code.

function multiply(a, b, c) {
    return a * b * c;
}
let numbers;
numbers = [2, 3, 4];
console.log(multiply(...numbers));

The output of the above example code is as follows −

24

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *