TypeScript Rest Parameters
Handle unlimited function arguments with type safety
📦 What are Rest Parameters?
Rest parameters allow functions to accept an indefinite number of arguments as an array. Using the spread operator (...), you can collect multiple arguments into a single typed array parameter.
// Rest parameter collects all arguments
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3));
console.log(sum(10, 20, 30, 40, 50));
Output:
6
150
Rest Parameter Features
Variable Arguments
Accept any number of arguments
function list(...items: string[]) {
return items;
}
Array Collection
Arguments collected as array
// numbers is an array
function add(...numbers: number[]) {
// Use array methods
}
Type Safety
All arguments must match type
sum(1, 2, 3); // ✓ Valid
sum(1, "2", 3); // ✗ Error
Must Be Last
Rest parameter must be final
function build(
name: string,
...tags: string[]
) { }
🔹 Basic Rest Parameters
Collect multiple arguments into an array:
function multiply(...numbers: number[]): number {
let result = 1;
for (const num of numbers) {
result *= num;
}
return result;
}
console.log(multiply(2, 3));
console.log(multiply(2, 3, 4));
console.log(multiply(1, 2, 3, 4, 5));
Output:
6
24
120
🔹 Rest Parameters with Regular Parameters
Combine regular and rest parameters:
function buildSentence(greeting: string, ...names: string[]): string {
if (names.length === 0) {
return `${greeting}!`;
}
return `${greeting}, ${names.join(" and ")}!`;
}
console.log(buildSentence("Hello"));
console.log(buildSentence("Welcome", "Alice"));
console.log(buildSentence("Hi", "Bob", "Charlie", "David"));
Output:
Hello!
Welcome, Alice!
Hi, Bob and Charlie and David!
🔹 Rest Parameters with Array Methods
Use array methods on rest parameters:
function getStats(...scores: number[]): string {
if (scores.length === 0) {
return "No scores provided";
}
const total = scores.reduce((sum, score) => sum + score, 0);
const average = total / scores.length;
const highest = Math.max(...scores);
const lowest = Math.min(...scores);
return `Total: ${total}, Average: ${average.toFixed(2)}, High: ${highest}, Low: ${lowest}`;
}
console.log(getStats(85, 92, 78, 95, 88));
Output:
Total: 438, Average: 87.60, High: 95, Low: 78
🔹 Rest Parameters with Different Types
Use rest parameters with various types:
// String rest parameters
function concatenate(...words: string[]): string {
return words.join(" ");
}
// Boolean rest parameters
function allTrue(...values: boolean[]): boolean {
return values.every(val => val === true);
}
// Mixed type with union
function logValues(...items: (string | number)[]): void {
items.forEach(item => console.log(`Value: ${item}`));
}
console.log(concatenate("Hello", "World", "from", "TypeScript"));
console.log(allTrue(true, true, true));
console.log(allTrue(true, false, true));
Output:
Hello World from TypeScript
true
false
🔹 Rest Parameters with Objects
Collect objects with rest parameters:
type User = {
name: string;
age: number;
};
function displayUsers(...users: User[]): void {
console.log(`Total users: ${users.length}`);
users.forEach((user, index) => {
console.log(`${index + 1}. ${user.name} (${user.age})`);
});
}
displayUsers(
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 28 }
);
Output:
Total users: 3
1. Alice (25)
2. Bob (30)
3. Charlie (28)
🔹 Practical Example: Logger Function
Create a flexible logging function:
function log(level: string, ...messages: string[]): void {
const timestamp = new Date().toLocaleTimeString();
const formattedMessages = messages.join(" | ");
console.log(`[${timestamp}] ${level.toUpperCase()}: ${formattedMessages}`);
}
log("info", "Application started");
log("warning", "Low memory", "Consider closing apps");
log("error", "Connection failed", "Retrying", "Attempt 1");
Output:
[12:30:45] INFO: Application started
[12:30:45] WARNING: Low memory | Consider closing apps
[12:30:45] ERROR: Connection failed | Retrying | Attempt 1
💡 Rest Parameter Rules:
- Only one rest parameter is allowed per function
- Rest parameter must be the last parameter
- Rest parameter is always an array type
- Use spread operator (...) to define rest parameters
- All arguments collected must match the specified type