Rest Parameters in TypeScript
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.
Similar Reads
TypeScript Rest Parameters and Arguments 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
2 min read
TypeScript Rest Arguments TypeScript rest arguments use the spread operator (...) to capture a variable number of function arguments into an array. This allows for flexible operations like merging, concatenating, or processing multiple inputs dynamically within a single function.Syntaxfunction function_name(...rest: type[])
2 min read
TypeScript Parameter Type Annotations TypeScript Parameter type annotations are used to specify the expected data types of function parameters. They provide a way to explicitly define the types of values that a function expects as arguments. Parameter type annotations are part of TypeScript's static typing system, and they help catch ty
2 min read
Interfaces in TypeScript TypeScript is a statically typed superset of JavaScript that adds optional types, classes, interfaces, and other features to help developers build robust and maintainable applications. One of the most powerful features of TypeScript is interfaces, which allow you to define the structure of objects,
4 min read
TypeScript Interfaces Type TypeScript Interfaces Type offers an alternative method for defining an object's type, allowing for a distinct naming approach. Syntax:interface InterfaceName { property1: type1; property2?: type2; readonly property3: type3; // ... method1(): returnType1; method2(): returnType2; // ...}Parameters:in
2 min read