TypeScript Tuples
A tuple is a special array type with a fixed number of elements where each position has its own specific type. Tuples are useful when you want to group a small, fixed set of related values together.
Unlike a regular array, the order and types of tuple elements matter. For example, a tuple `[string, number]` must always have a string first and a number second.
let point: [number, number] = [10, 20];Declaring a tuple
You declare a tuple type by listing the expected types in square brackets in order, such as `let user: [string, number] = ["Alice", 30];`.
Accessing tuple elements
You access tuple elements by index just like arrays, and TypeScript knows the exact type at each index, giving you accurate type checking.
let user: [string, number] = ["Alice", 30];
console.log(`${user[0]} is ${user[1]} years old`);Alice is 30 years oldThe tuple guarantees the first element is a string and the second is a number.
let point: [number, number] = [3, 4];
const [x, y] = point;
console.log(x + y);7Tuples can be destructured just like regular arrays.
Key points
- Tuples have a fixed length and fixed type at each position.
- Order matters: [string, number] is different from [number, string].
- Tuples are declared with square brackets listing each element's type.
- Tuples can be destructured like normal arrays.
