TypeScript Rest Parameters

TypeScript Rest parameters allows a function to take unlimited parameters. Rest parameters are used when we are designing a function and we do not know how many parameters are required.

Rest parameters feature group parameters into a single variable and we can access parameters inside a function just like an array of parameters. There is only one rest parameter allowed in a function.

Syntax

We have to put three dots before the parameter name and rest parameter must be the last parameter of the function. Below is the syntax of using Rest parameters:

function funcName(...restParameters) {
    //...
}

Rest Parameters Types

We can also provide data types to rest parameters. A rest parameter must be an array type like shown below:

function funcName(...restParameters: string[]) {
    //...
}

function funcName2(...restParameters: number[]) {
    //...
}

In above examples, we have assigned string and number array type to ‘restParameter’ parameter.

Rest Parameters Example

function printNames(...names: string[]) {
    for (let i = 0; i < names.length; ++i) {
        console.log(names[i] + ",");
    }
}

printNames("Michael");
printNames("Michael", "Dana", "Ambika");
printNames("George", "Riya", "Pooja", "Priyanka", "Raj", "Neha", "Cherese");

In above example, we have declared a function named “printNames”. This function takes a names rest parameter which is of string array type.

We can check total number of parameters passed by length property of names and we can access each parameter by using index of an array.

In last lines, we call function with different parameters. In first function we pass only one string. In second function we pass three names. In third function we pass seven names. We can pass unlimited number of parameters but of same type must match of the rest parameter data type.

Required Parameters

Rest parameters can be combined with required parameters. Required parameters must come before the rest parameter. Below is the example:

function printNames(group: number, ...names: string[]) {
    //..
}

printNames(1, "Michael");
printNames(2, "Michael", "Dana", "Ambika");
printNames(3, "George", "Riya", "Pooja", "Priyanka", "Raj", "Neha", "Cherese");

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.