Rest Parameters with Tuple Types
What you'll learn: How to use tuple types to enforce specific patterns when a function accepts a variable number of arguments.
Controlling Variable Argument Patterns
You already know that rest parameters collect multiple arguments into an array, and you can type that array. But what if you want to enforce a specific pattern in those arguments — like "the first must be a number, the second a string, and any remaining ones must be booleans"?
This is where tuple types shine with rest parameters.
Enforcing Argument Patterns with Tuples
Instead of typing a rest parameter as a general array, you can use a tuple type to specify exactly what the arguments should look like:
function logEntry(...args: [number, string, ...boolean[]]): void {
const [id, message, ...flags] = args;
console.log(`ID: ${id}, Message: ${message}, Flags: ${flags}`);
}
logEntry(1, "hello", true, false); // ✓ Valid
logEntry(2, "world"); // ✓ Valid (booleans optional)
logEntry(3, "test", true); // ✓ Valid
logEntry("oops", "test", true); // ✗ Error: first must be number
logEntry(4, 5, true); // ✗ Error: second must be string
The tuple [number, string, ...boolean[]] means: "first arg is a number, second is a string, then zero or more booleans."
Why This Matters
Without tuple types, rest parameters accept any arguments matching the array element type. With tuples, you get fine-grained control over argument order and types while still allowing variable length.
Key Takeaway: Tuple types with rest parameters let you enforce specific argument patterns (position and type) while keeping the flexibility of variable-length argument lists.