Spreading Tuples with Known Length
What you'll learn: How TypeScript perfectly matches tuple elements to function parameters when you spread a tuple into a function call.
When you've defined a tuple with a known, fixed length, TypeScript can "unpack" it intelligently when you spread it into a function. Each element in the tuple maps directly to the corresponding parameter position, preserving both the type and the order.
The Perfect Match
Imagine you have a function that expects three specific parameters: a name, an age, and a status flag. If you have a tuple that contains exactly those three values in the same order, spreading it into the function call is like handing over a perfectly organized box where each item goes to its designated slot.
function greet(name: string, age: number, isActive: boolean): string {
return `${name} is ${age} and ${isActive ? 'active' : 'inactive'}`;
}
const userInfo: [string, number, boolean] = ["Alice", 30, true];
// TypeScript knows the tuple has exactly 3 elements
// matching the 3 parameters perfectly
const result = greet(...userInfo); // ✓ Valid!
TypeScript's Checking Power
TypeScript verifies that the tuple length matches the parameter count. If your tuple has too many or too few elements, or if the types don't align with the parameter types, you'll get a compile-time error:
const wrongLength: [string, number] = ["Bob", 25];
// greet(...wrongLength); // ✗ Error: Expected 3 elements, got 2
const wrongTypes: [number, string, boolean] = [30, "Alice", true];
// greet(...wrongTypes); // ✗ Error: Types don't match
Key Takeaway: When you spread a tuple with a known length into a function call, TypeScript maps each tuple element to its corresponding parameter position, ensuring type safety and exact argument matching.