Rest parameters are a powerful feature in TypeScript that allow functions to accept an indefinite number of arguments as an array. They provide a clean and flexible way to handle variable-length argument lists.
To declare a rest parameter, use the ellipsis (...) followed by the parameter name. This parameter must be the last in the function's parameter list.
function exampleFunction(...args: type[]): returnType {
// Function body
}
The rest parameter is treated as an array inside the function, allowing you to use array methods and access individual elements.
arguments
objectfunction sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(4, 5, 6, 7)); // Output: 22
In this example, the sum
function can accept any number of arguments, which are then summed up using the reduce
method.
function log(message: string, ...details: any[]): void {
console.log(message);
if (details.length > 0) {
console.log("Additional details:", details);
}
}
log("User logged in"); // Output: User logged in
log("Error occurred", "File not found", 404); // Output: Error occurred \n Additional details: ["File not found", 404]
This logging function demonstrates how rest parameters can be used alongside regular parameters. It allows for flexible logging with optional additional details.
arguments
object for better type checking and readabilityTo further enhance your understanding of TypeScript functions, explore these related topics:
By mastering rest parameters, you'll gain more flexibility in function design and improve your overall TypeScript coding skills.