Explain about rest parameters and arguments in TypeScript


TypeScript is a feature-rich programming language, and it is necessary to know all features of TypeScript while developing web applications with TypeScript. One such feature is the rest of the parameters and arguments in TypeScript.

This tutorial will teach us to use the rest parameters and arguments in TypeScript with various code examples.

What are the Rest Parameters and Arguments?

The rest parameter is used to pass the multiple arguments to the function when we don’t know how many arguments we need to pass to the function. The rest parameter name is written, followed by ‘…’ (three dots).

When we pass the multiple arguments while calling the function, it is called the rest arguments.

Rules for using the Rest Parameters and Arguments

  • The rest parameter accepts the zero to N number of arguments.

  • Always use the rest parameter at last in the parameter list.

  • The function contains only a single rest parameter.

  • The type of the rest parameter should be an array of strings, numbers, boolean, objects, user-defined types, etc.

  • The rest parameter's name can be any like a normal parameter name.

Syntax

Users can follow the syntax below to use the rest parameter in TypeScript.

function func1(...numbers: number[]) {
}
func1(1, 2, 3, 4, 5);

In the above syntax, the func1() function contains the ‘numbers’ named rest parameter, an array of unspecified elements. After that, we called the function by passing the multiple numbers as an argument.

Example

In the example below, we created the changeSign() function to change the sign of the number, which takes the ‘nums’ rest parameter. In the changeSign() function, we use the map() method to map the number with the opposite sign to the updated array and return the new array from the function.

We call the changeSign() parameter by passing the different number of arguments, and in the output, we can observe that it prints the output without showing any error. In this way, we can pass multiple numbers of arguments to the function while using the rest parameter.

// Rest parameters in typescript to change sign of numbers
function changeSign(...nums: number[]): number[] {
   return nums.map((num) => num * -1);
}

let changedSigns = changeSign(1, -2, 3, 4, 5);
console.log(changedSigns);

changedSigns = changeSign(10, -12);
console.log(changedSigns);

On compiling, it will generate the following JavaScript code −

function changeSign() {
   var nums = [];
   for (var _i = 0; _i < arguments.length; _i++) {
      nums[_i] = arguments[_i];
   }
   return nums.map(function (num) { return num * -1; });
}
var changedSigns = changeSign(1, -2, 3, 4, 5);
console.log(changedSigns);
changedSigns = changeSign(10, -12);
console.log(changedSigns);

Example

In the example below, the stringMerger() function takes two parameters. The first is the string parameter, and the second is a rest parameter of the string type. We always need to pass the one-string value while calling the function due to the first string parameter. After that, we can pass the unspecified number of arguments that the rest parameters will handle.

In the function, we traverse the string array, which we get via the rest parameter, and merge all array elements to str1. At last, we return the str1 string.

We executed the stringMerger() function by passing the multiple strings. The str1 will handle the first argument, and str2 will handle all other arguments we can observe in the output.

// Function to concatenate strings
function stringMerger(str1: string, ...str2: string[]): string {
   for(let i=0; i<str2.length; i++){
      str1 += str2[i];
   }
   return str1;
}

// Executing the function with different number of arguments
let finalStr = stringMerger("Hello", " ", "World", "!");
console.log(finalStr);

finalStr = stringMerger("Hello", " ", "World", "!", " ", "How", " ", "are", " ", "you", "?");
console.log(finalStr);

finalStr = stringMerger("ABCDEF");
console.log(finalStr);

On compiling, it will generate the following JavaScript code −

// Function to concatenate strings
function stringMerger(str1) {
   var str2 = [];
   for (var _i = 1; _i < arguments.length; _i++) {
      str2[_i - 1] = arguments[_i];
   }
   for (var i = 0; i < str2.length; i++) {
      str1 += str2[i];
   }
   return str1;
}
// Executing the function with different number of arguments
var finalStr = stringMerger("Hello", " ", "World", "!");
console.log(finalStr);
finalStr = stringMerger("Hello", " ", "World", "!", " ", "How", " ", "are", " ", "you", "?");
console.log(finalStr);
finalStr = stringMerger("ABCDEF");
console.log(finalStr);

Example

The example below demonstrates to use of the rest parameter of the user-defined data type. We have defined the ‘User’ interface containing the ‘name’ and ‘id’ property.

The createUser() function takes the rest parameter of the ‘User’ type and prints all user’s details. Also, we created multiple user objects.

We executed the createUser() function three times and passed the different number of User objects as arguments. In the output, we can see that it prints the user details without any error.

// Creating the interface for user-defined types
interface User {
   name: string;
   id: number;
}

// Rest parameter of User type
function createUser(...users: User[]) {
   
   // Printing all user details
   users.forEach(user => {
      console.log(`Name: ${user.name}, ID: ${user.id}`);
   });
}

// Creating user objects
let user1: User = { name: "Man", id: 1 };
let user2: User = { name: "Shah", id: 2 };
let user3: User = { name: "Shubham", id: 3 };
let user4: User = { name: "Ram", id: 4 };

console.log("First function call!")
createUser(user1, user2, user3, user4);

console.log("Second function call!")
createUser(user1, user2);

console.log("Third function call!")
createUser(user1, user2, user3);

On compiling, it will generate the following JavaScript code −

// Rest parameter of User type
function createUser() {
   var users = [];
   for (var _i = 0; _i < arguments.length; _i++) {
       users[_i] = arguments[_i];
   }
   
   // Printing all user details
   users.forEach(function (user) {
      console.log("Name: ".concat(user.name, ", ID: ").concat(user.id));
   });
}

// Creating user objects
var user1 = { name: "Man", id: 1 };
var user2 = { name: "Shah", id: 2 };
var user3 = { name: "Shubham", id: 3 };
var user4 = { name: "Ram", id: 4 };
console.log("First function call!");
createUser(user1, user2, user3, user4);
console.log("Second function call!");
createUser(user1, user2);
console.log("Third function call!");
createUser(user1, user2, user3);

We learned to use the rest parameters in TypeScript. The main purpose of using the rest parameters is to handle the arguments when we are unsure about passing the number of arguments to the function. Basically, it is used to handle the optional arguments.

Updated on: 14-Jul-2023

343 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements