Rest Parameters in TypeScript (original) (raw)

Last Updated : 22 Jan, 2025

**Rest parameters in TypeScript enable functions to handle an unlimited number of arguments by grouping them into an array. They are defined using ... and must be the last parameter.

**Syntax

function function_name(...rest: type[]) {
// Type of the is the type of the array.
}

**Parameters:

function sum(...numbers: number[]): number { return numbers.reduce((total, num) => total + num, 0); }

console.log(sum(1, 2, 3)); console.log(sum(10, 20));

`

**Output:

6
30

Calculating the Average of Numbers

TypeScript `

function average(...numbers: number[]): number { let total = 0; for (let num of numbers) { total += num; } return numbers.length === 0 ? 0 : total / numbers.length; }

console.log("Average of the given numbers is:", average(10, 20, 30, 60)); console.log("Average of the given numbers is:", average(5, 6)); console.log("Average of the given numbers is:", average(4));

`

**Output:

Average of the given numbers is : 30
Average of the given numbers is : 5.5
Average of the given numbers is : 4

**Concatenating Strings

TypeScript `

function joinStrings(...strings: string[]): string { return strings.join(', '); }

console.log(joinStrings("rachel", "john", "peter") + " are mathematicians"); console.log(joinStrings("sarah", "joseph") + " are coders");

`

**Output:

rachel, john, peter are mathematicians
sarah, joseph are coders

**Incorrect Usage of Rest Parameters

TypeScript ``

// Incorrect usage - will raise a compiler error function job(...people: string[], jobTitle: string): void { console.log(${people.join(', ')} are ${jobTitle}); }

// Uncommenting the below line will cause a compiler error // job("rachel", "john", "peter", "mathematicians");

``

**Output: Typescript compiler raised the error.

main.ts(2,14): error TS1014: A rest parameter must be last in a parameter list.

Best Practices for Using TypeScript Rest Parameters