Functions in TypeScript
Rest Parameters
Master variadic functions in TypeScript using rest parameters (...args), typing rest array elements, and tuple rest parameters.
In JavaScript and TypeScript, Rest Parameters (...args) allow functions to accept an arbitrary number of arguments as a single, strongly-typed array or tuple.
1. Syntax for Rest Parameters
Rest parameters are declared with three dots (...) before the parameter name, and must be annotated as an array (T[]) or tuple type.
2. Rest Parameter Rules
1. Only One Rest Parameter: A function can have at most one rest parameter. 2. Must Be Last Parameter: The rest parameter must be the final parameter in the function signature.
3. Tuple Rest Parameters (Variadic Tuple Parameters)
TypeScript allows typing rest parameters using Tuple Types to enforce position-specific argument signatures for variadic functions:
4. Spreading Arrays into Rest Parameters
When passing an array variable into a function expecting rest parameters, TypeScript requires the array to be typed properly or asserted with as const to avoid tuple mismatch errors.
5. Interactive Code Playground
Test rest parameters below:
6. Common Pitfalls & Edge Cases
...args) with Arguments Object:arguments object. In TypeScript, prefer rest parameters (...args: T[]) because arguments is un-typed (any) and unavailable in arrow functions.
7. Summary Table
| Feature | Rest Parameter (...args: T[]) |
|---|---|
| Inferred Inside Function | Standard Array (T[]) or Tuple |
| Position in Parameters | Must be the last parameter |
as const or tuple type |