Functions
TS Rest Parameters
Using Rest Parameters
TypeScript rest parameters collect arguments typed as arrays.
What Are Rest Parameters?
Rest parameters in TypeScript allow you to represent an indefinite number of arguments as an array. They are useful when you want a function to accept more arguments than the number of formally declared parameters. The syntax uses three dots (...
) followed by the name of the array that will contain the rest of the arguments.
Syntax and Type Annotations
To define rest parameters in a TypeScript function, use the rest syntax (...
) before the parameter name. You should also specify the type of the elements in the array. The array type is defined by appending square brackets to the element type, like number[]
or string[]
.
Using Rest Parameters with Other Parameters
Rest parameters must be the last in the parameter list. You can have other parameters before the rest parameter, but not after. This ensures that all remaining arguments are captured by the rest parameter.
Practical Use Cases
Rest parameters are ideal when writing functions that work with multiple arguments such as mathematical operations, string manipulations, or handling event listeners in DOM programming. They provide flexibility and make your functions more adaptable to different use cases.
Functions
- Previous
- Default Parameters
- Next
- Optional Parameters