Rest Parameters Basics
You'll learn how to gather multiple function arguments into a single typed array.
What Are Rest Parameters?
Imagine a function that needs to accept any number of values—like a shopping cart that can hold 1 item or 100. In JavaScript and TypeScript, rest parameters let you capture all remaining arguments into an array using the ... syntax.
The Rest Parameter Syntax
A rest parameter collects all extra arguments passed to a function into a single array:
function sum(...numbers: number[]): number {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
sum(1, 2, 3); // 6
sum(10, 20, 30, 40); // 100
sum(); // 0 (empty array)
The ...numbers syntax tells TypeScript: "gather all arguments into an array called numbers."
Type Inference with Rest Parameters
TypeScript automatically infers rest parameters as arrays:
function logAll(...items: string[]): void {
items.forEach(item => console.log(item));
}
// items has type string[] inside the function
logAll("hello", "world");
Rest Parameters Must Come Last
Just like optional parameters, rest parameters must appear at the end:
function greet(greeting: string, ...names: string[]): string {
return `${greeting}, ${names.join(" and ")}`;
}
greet("Hello", "Alice", "Bob"); // "Hello, Alice and Bob"
Key Takeaway: Rest parameters use ...paramName: type[] syntax to capture variable-length argument lists into a typed array, and they must always be the last parameter in the function signature.