Rest Parameters as Arrays
You'll learn how TypeScript treats rest parameters as typed arrays, letting you accept any number of arguments with type safety.
What Are Rest Parameters?
In JavaScript, the rest parameter syntax (...paramName) lets a function accept unlimited arguments and collects them into an array. TypeScript adds type safety to this pattern by treating rest parameters as typed arrays.
When you use ... in a function parameter list, TypeScript automatically infers or requires an array type for those collected arguments.
How It Works
function sum(...numbers: number[]): number {
return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3); // ✓ OK: numbers = [1, 2, 3]
sum(10, 20); // ✓ OK: numbers = [10, 20]
sum(); // ✓ OK: numbers = []
sum(1, "two", 3); // ✗ Error: "two" is not a number
The ...numbers: number[] annotation means "collect all remaining arguments into an array of numbers." Inside the function, numbers is just a regular typed array—you can use .reduce(), .map(), .length, and all array methods.
Mixing Regular and Rest Parameters
Rest parameters must come last, but you can combine them with regular parameters:
function greet(greeting: string, ...names: string[]): void {
console.log(`${greeting}, ${names.join(" and ")}!`);
}
greet("Hello", "Alice"); // "Hello, Alice!"
greet("Hello", "Bob", "Charlie"); // "Hello, Bob and Charlie!"
Key Takeaway: Rest parameters are typed arrays that collect variable arguments, giving you flexibility with full type safety on every element.