TypeScript Tuples
A tuple is a special array type in TypeScript where the number of elements and the type of each element are fixed and known in advance.
What Is a Tuple?
In JavaScript, arrays can hold any mix of values, but TypeScript tuples let you describe an array with a precise shape: the exact number of positions and the exact type expected at each position. This is useful whenever a value is 'a pair' or 'a fixed record' rather than an open-ended list.
Declaring a Tuple
let point: [number, number] = [10, 20];
let nameAge: [string, number] = ["Aria", 29];
// Error: Type 'string' is not assignable to type 'number'
// let bad: [string, number] = ["Aria", "29"];Accessing and Destructuring Tuples
Tuple elements are accessed by index just like arrays, and each index has its own known type. Destructuring works well with tuples because the position of each variable maps directly to the position in the tuple.
Destructuring a Tuple
function getCoordinates(): [number, number] {
return [51.5074, -0.1278];
}
const [latitude, longitude] = getCoordinates();
console.log(latitude.toFixed(2)); // "51.51"
console.log(longitude.toFixed(2)); // "-0.13"Named Tuple Members
TypeScript allows you to label tuple positions for readability. The labels don't change the runtime behavior — they only appear in tooling like autocomplete and hover documentation.
Labeled Tuple Elements
type HttpResponse = [status: number, body: string, headers: Record<string, string>];
function parseResponse(res: HttpResponse) {
const [status, body, headers] = res;
return { ok: status < 400, body, headers };
}Optional and Rest Elements in Tuples
Tuples can have optional elements marked with a question mark, and a rest element that captures any number of trailing items of a given type. This combines the strictness of tuples with the flexibility of arrays.
- [number, number?] — a tuple with one required and one optional number
- [string, ...number[]] — a required string followed by any number of numbers
- [boolean, string?, ...number[]] — mixing required, optional, and rest positions
- readonly [number, number] — a tuple whose contents cannot be reassigned
Tuples vs Arrays
Realistic Use Case: useState-Style Return Values
A very common real-world pattern is a function that returns a value and an updater together, similar to React's useState. Tuples make this pattern fully type-safe on both sides.
A Tuple-Returning Hook-Like Function
function createCounter(initial: number): [() => number, (next: number) => void] {
let count = initial;
const getCount = () => count;
const setCount = (next: number) => { count = next; };
return [getCount, setCount];
}
const [getCount, setCount] = createCounter(0);
setCount(5);
console.log(getCount()); // 5Exercise: TypeScript Tuples
What distinguishes a tuple from a regular array in TypeScript?