Rest Parameters in TypeScript

TypeScript introduced rest parameters to accommodate n number of parameters easily.

When the number of parameters that a function will receive is not known or can vary, we can use rest parameters. In JavaScript, this is achieved with the "arguments" variable. However, with TypeScript, we can use the rest parameter denoted by ellipsis ...

We can pass zero or more arguments to the rest parameter. The compiler will create an array of arguments with the rest parameter name provided by us.

function Greet(greeting: string, ...names: string[]) {
    return greeting + " " + names.join(", ") + "!";
}

Greet("Hello", "Steve", "Bill"); // returns "Hello Steve, Bill!"

Greet("Hello");// returns "Hello !"

In the above example, we have a function with two parameters: greeting and names. Here, names is a rest parameter denoted by ellipses .... While calling the function, we first pass "Steve", "Bill" as the rest parameters. These are combined into a string array by joining the elements of the names array. Hence, it returns "Hello Steve, Bill!". During the second function call, we do not pass any arguments as the rest parameters. This is accepted by the compiler and hence the output is "Hello !"

The rest parameters can be used in functions, arrow functions or classes.

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

Greet("Hello", "Steve", "Bill"); // returns "Hello Steve, Bill!"

Greet("Hello");// returns "Hello !"

Remember, rest parameters must come last in the function definition, otherwise, the TypeScript compiler will show an error. The following is not valid.

function Greet(...names: string[], greeting: string) {  // Compiler Error
    return greeting + " " + names.join(", ") + "!";
}