TypeScript Rest Parameters: Handling Flexible Argument Lists

Discover how TypeScript's rest parameters, using the ... spread operator, allow you to manage functions with a variable number of arguments. Learn how to collect additional arguments into an array for more flexible and dynamic function handling.



TypeScript Rest Parameters

Rest parameters in TypeScript provide a convenient way to handle functions with an indefinite number of arguments. By using the ... spread operator, you can collect extra arguments into an array.

Basic Usage

Syntax

function sum(...numbers: number[]): number {
  return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3)); // Output: 6
console.log(sum()); // Output: 0
Output

6
0

Combining with Regular Parameters

Syntax

function greet(greeting: string, ...names: string[]): string {
  return `${greeting} ${names.join(', ')}!`;
}

console.log(greet('Hello', 'Alice', 'Bob', 'Charlie')); // Output: Hello Alice, Bob, Charlie!
Output

Hello Alice, Bob, Charlie!

Destructuring Rest Parameters

Syntax

function processOrder(orderId: number, ...items: [string, number][]) {
  // Access items as an array of tuples
}
Output

No direct output for this example.

Important Considerations

  • Single Rest Parameter: A function can have only one rest parameter.
  • Last Parameter: The rest parameter must be the last parameter in the function's parameter list.
  • Type Safety: The type of the rest parameter is an array of the specified type.
  • Empty Argument List: You can pass zero arguments to a rest parameter.

Best Practices

  • Use descriptive names for rest parameters to improve code readability.
  • Consider using default parameters for optional arguments before resorting to rest parameters.
  • Leverage TypeScript's type system to ensure type safety for rest parameters.

Additional Examples

Syntax

function logArgs(...args: any[]) {
  console.log(args);
}

logArgs('hello', 42, true); // Output: ['hello', 42, true]
Output

['hello', 42, true]
Syntax

function createElement(tag: string, ...attributes: [string, any][]) {
  // ... create element with attributes
}
Output

No direct output for this example.