Rest Parameters in TypeScript

Rest Parameters in TypeScript allow us to accept a variable number of arguments as an array. TypeScript introduced this feature in ES6. It is now the preferred way to access the variable number of arguments or the number of arguments is not known.

Rest Parameters

We use the parameters to access the arguments inside the function. TypeScript expects us the provide the same number of arguments as there are parameters. We can supply less number of arguments only if the parameters are declared as optional Parameters. However, typescript will not allow us to pass more arguments than declared in the parameters.

You can see it from the following example. As you can see TypeScript throws an error if the number of arguments does not match the parameters

But JavaScript allows passing a variable number of arguments and never throws any errors. We can use the Arguments object or Rest Parameters in JavaScript to access those arguments.

Using Rest Parameters

Rest Parameters in TypeScript lets us store the extra arguments that we supply to the function into an array.

Syntax

The syntax is shown below. We prefix the rest Parameter with ... (three dots) followed by the name of the rest parameter.

In the above syntax args is the rest parameter, while a & b are normal parameters. We must provide an array type to the rest parameter.

TypeScript assigns the arguments to parameters starting from left to right. First, it assigns the values to the regular parameters a & b. When it encounters a rest parameter it creates an array of all remaining arguments and assigns it to the Rest Parameter i.e. args.

You can pass any number of arguments to a rest parameter. You can even pass none.

The following function fnRest declares args as the rest parameter along with regular parameters a & b. As you can see the first two arguments (1 & 2 ) are mapped in the parameters a & b. The remaining arguments are stored as an array in the rest Parameter args.

Rules of Rest Parameters

Even if there is just one extra argument, it will be saved as a single element of an array.

If there is no argument provided then we get an empty array

The Rest Parameters must appear last in the Parameter list.

There can be only one rest parameter in a function.

Rest Parameters Example

The following example nums is a rest parameter. We invoke AddNum many arguments. All of them are captured in the nums array. We then loop through it using for loop and calculate the sum

Another example

Reference

Rest parameters and arguments

Leave a Comment

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.

Scroll to Top