Course contentsShow
← TypeScript
Lesson 1391 of 1,79632. Advanced PatternsFree lesson

Variadic Tuples in Function Signatures

Typing functions that forward arguments while preserving exact parameter types and order.

Variadic Tuples in Function Signatures

What you'll learn: How to type functions that forward or transform arguments while preserving their exact parameter types and order.

The Problem: Losing Type Information

Imagine you want to write a wrapper function that calls another function with the same arguments. Without variadic tuples, you'd lose precise type information about what parameters the wrapped function actually expects.

Before variadic tuples, you might use any[] or overly generic approaches that sacrifice type safety. Now you can preserve the exact signature.

How Variadic Tuples Work in Functions

Variadic tuple types let you capture a function's parameters as a tuple type, then spread them in another signature. Think of it like a type-level "arguments forwarding" mechanism.

The pattern typically looks like this:

function wrapper<T extends any[]>(
  fn: (...args: T) => void,
  ...args: T
): void {
  fn(...args);
}

Here, T captures the exact parameter list of fn, and ...args: T requires you to pass those same parameters to wrapper.

Real-World Example: Logger Wrapper

function logged<Args extends any[]>(
  fn: (...args: Args) => void
): (...args: Args) => void {
  return (...args: Args) => {
    console.log('Calling with:', args);
    fn(...args);
  };
}

const greet = (name: string, age: number) => {
  console.log(`Hello ${name}, age ${age}`);
};

const loggedGreet = logged(greet);
loggedGreet('Alice', 30); // ✓ Type-safe!
// loggedGreet('Bob'); // ✗ Error: Expected 2 arguments

The wrapper preserves the exact parameters: string and number, in that order.

Why This Matters

Without variadic tuples, you'd lose autocomplete, parameter names, and type checking when forwarding arguments. This pattern appears everywhere: middleware, decorators, event handlers, retry logic, and any higher-order function that wraps another.

Key Takeaway: Variadic tuples in function signatures let you capture and forward exact parameter lists through generic type parameters, maintaining complete type safety when wrapping or transforming functions.