Spread Operator in Function Calls
You'll learn how TypeScript validates types when you spread an array into function arguments.
When you call a function, you can use the spread operator (...) to unpack an array's elements as individual arguments. TypeScript checks that the array's element types match what the function expects for its parameters.
The Core Idea
Think of spreading like unpacking a box of items onto a table. If a function expects three specific items in specific positions, TypeScript verifies that your box contains the right types in the right order.
function greet(first: string, last: string, age: number) {
console.log(`${first} ${last}, age ${age}`);
}
const args: [string, string, number] = ["John", "Doe", 30];
greet(...args); // ✓ Valid - tuple matches parameter types exactly
const wrongArgs: [string, number] = ["John", 30];
greet(...wrongArgs); // ✗ Error - not enough arguments
How TypeScript Types the Spread
TypeScript examines the array type being spread and maps its elements to function parameters:
- With tuples, each position maps directly to a parameter
- With regular arrays, TypeScript treats it as spreading an unknown number of elements
function add(a: number, b: number): number {
return a + b;
}
const tuple: [number, number] = [5, 10];
add(...tuple); // ✓ Works - tuple has exactly 2 numbers
const array: number[] = [5, 10];
add(...array); // ✗ Error - array length is unknown at compile time
This is why tuples work so well with spread in function calls—their fixed length gives TypeScript certainty about matching parameters.
Key Takeaway: TypeScript type-checks spread expressions by matching the spread array's element types to the function's parameter types, with tuples providing precise, position-based validation.