Rest Parameters in Callback Functions
You'll learn how to type rest parameters when they appear in higher-order functions and callbacks, enabling flexible event handlers and middleware patterns.
The Core Idea
Rest parameters aren't just for regular functions—they're especially powerful in callbacks passed to higher-order functions. When you write event handlers, middleware, or utility functions that accept callbacks, those callbacks often need to accept a variable number of arguments. TypeScript lets you type these rest parameters precisely, ensuring type safety throughout the callback chain.
Think of it like a restaurant server who can carry any number of dishes on a tray. The kitchen (higher-order function) doesn't know exactly how many dishes will be needed, but the server (callback) can handle however many come their way—and you can still label what type each dish is.
Basic Callback with Rest Parameters
function processItems(...items: string[]): void {
console.log(`Processing ${items.length} items`);
}
function forEach(callback: (...args: string[]) => void, ...values: string[]): void {
callback(...values);
}
forEach(processItems, "apple", "banana", "cherry");
Event Handler Pattern
type EventHandler = (...args: number[]) => void;
function onClick(handler: EventHandler): void {
handler(100, 200); // Mouse coordinates
}
onClick((...coords: number[]) => {
console.log(`Clicked at: ${coords}`);
});
Middleware Example
type Middleware = (...params: string[]) => void;
function applyMiddleware(fn: Middleware, ...args: string[]): void {
fn(...args);
}
applyMiddleware((...data) => console.log(data), "req", "res", "next");
Key Takeaway: Typing rest parameters in callbacks ensures your higher-order functions maintain type safety while supporting flexible argument passing—critical for event systems and middleware architectures.