Tuples
What
A tuple is a specialized array where the length is fixed and each position (index) has a specific, known type.
How
You define a tuple by specifying the types within square brackets. It is critical to provide an explicit type annotation, otherwise TypeScript will infer the variable as a standard array:
// Explicit tuple
const nameAndAge: [string, number] = ["Rose Tyler", 24];
// Inferred as (string | number)[] - NOT a tuple
const inferred = ["Rose Tyler", 24];
Why
Tuples are much safer than arrays for small collections of related data. Because the types of each index are known, TypeScript can prevent you from accidentally assigning a string to a position that should be a number.
Summary
Always explicitly type your tuples to ensure TypeScript enforces the correct length and positional types.