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[]).
- 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
- 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
- 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
- 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.