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.
- Allow flexible and dynamic input handling in functions.
- Simplify working with multiple arguments without specifying them individually.
**Syntax
function function_name(...rest: type[]) {
// Type of the is the type of the array.
}
**Parameters:
- **functionName: The name of your function.
- ****...rest:** The rest parameter that collects all additional arguments into an array.
- **type[]: Specifies the type of elements in the rest array (e.g., number[], string[]). JavaScript `
function sum(...numbers: number[]): number { return numbers.reduce((total, num) => total + num, 0); }
console.log(sum(1, 2, 3)); console.log(sum(10, 20));
`
- The sum function uses the rest parameter ...numbers to collect all arguments passed to it into an array of type number[].
- The reduce method is applied to the numbers array, adding all its elements together to compute the total.
**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));
`
- The average function uses a rest parameter ...numbers to accept any number of numeric arguments.
- It calculates the total sum of these numbers and returns their average.
**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");
`
- The joinStrings function accepts multiple string arguments using a rest parameter.
- It concatenates them into a single string, separated by commas.
**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");
``
- In this example, the rest parameter ...people is not placed at the end of the parameter list.
- TypeScript requires rest parameters to be the last parameter; otherwise, a compiler error occurs.
**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
- **Place Rest Parameters Last: Always define rest parameters at the end of the parameter list to ensure correct function behavior.
- **Use Appropriate Types: Specify the correct array type for rest parameters to maintain type safety and code clarity.
- **Limit to One Rest Parameter: A function should have only one rest parameter to avoid complexity and potential errors.
- **Avoid Overuse: Use rest parameters judiciously; overuse can lead to code that is hard to understand and maintain.