Open In App

TypeScript Rest Parameters and Arguments

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript Rest Parameters allow functions to accept an indefinite number of arguments of the same type, collecting them into an array. Arguments refer to the actual values passed to a function when it’s invoked, while Rest Parameters provide a way to handle multiple arguments as an array within the function.

Rest Parameters

A rest parameter allows us to pass zero or any number of arguments of the specified type to a function. In the function definition where we specify function parameters rest of the parameters should always come at last or the typescript compiler will raise errors.

  • Rest Parameter allows us to accept zero or more arguments of the specified type.
  • A function (or a method) has only one rest parameter.
  • This parameter appears at last in the function’s specified parameter list.
  • Since here it is TypeScript being into the picture, the type of rest parameter is of an Array type (further the array could be string data type or number data type or anything).

Syntax

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

Parameters

  • function_name: Function’s identifier, used for calling and referencing the function within your code.
  • …rest_parameter_name: Collects multiple arguments into an array named rest_parameter_name.
  • type[]: Specifies the expected data type for elements stored in the rest_parameter_name array.

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

Javascript




function getSum(...numbers: number[]): number {
    return numbers.reduce((total, num) =>
        total + num, 0);
}
  
const result = getSum(10, 20, 30, 40, 50);
console.log(result);


Output:

150

Rest Arguments

  • These are arguments that we pass in while merging two data types (suppose concatenation of two arrays) using the same “…” (triple dots).
  • These types of arguments are generally used for merging or concatenation or for any other operational purpose by itself.

Syntax

let generateGreeting = (greeting: string, ...names: string[]): string => {
    return greeting + " " + names.join(", ") + "!";
}

Example: In this example, we will concatenate several strings which are passed inside the function as arguments.

Javascript




let generateGreeting = 
    (greeting: string, ...names: string[]): string => {
    return greeting + " " + names.join(", ") + "!";
}
  
// Function call
console.log(generateGreeting("GeeksforGeeks ",
                             "is a computer science portal "));


Output:

GeeksforGeeks  is a computer science portal !

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads