Sub topic 6
Tuples: Fixed Length, Typed Positions
Assume you know basic JavaScript arrays, TypeScript annotations, and union types. This chapter focuses on tuple types: arrays whose length and position types are known in advance.
What a tuple is
A tuple is a TypeScript type for a fixed number of elements where each position can have a different type. Write the types inside square brackets:
type Point = [number, number];
type UserRecord = [id: number, name: string, active: boolean];
const origin: Point = [0, 0];
const user: UserRecord = [42, "Ada", true];Point must contain exactly two numbers. UserRecord must contain a number, then a string, then a boolean.
TypeScript checks both the number of elements and their positions:
const point: Point = [10, 20];
// Error: the first element must be a number
// const invalidType: Point = ["10", 20];
// Error: Point requires two elements
// const invalidLength: Point = [10];The same type cannot accept the elements in a different order:
// Error: the second element must be a number
// const reversed: Point = ["north", 10];Reading and destructuring tuples
TypeScript uses the position to infer the type when you read an element:
type Coordinate = [number, number];
const location: Coordinate = [12.5, af 8.75];
const latitude = location[0]; // number
const longitude = location[1]; // numberEach variable has type number because both tuple positions are numbers. A tuple with different position types shows the distinction more clearly:
type Entry = [number, string];
const entry: Entry = [7, "pending"];
const key = entry[0]; // number
const status = entry[1]; // string
const [id, state] = entry;
// id: number
// state: stringDestructuring assigns each variable from its corresponding position. This is useful when a function returns a small, fixed group of related values:
function splitName(fullName: string): [first: string, last: string] {
const parts = fullName.trim().split(" ");
return [parts[0], parts[parts.length - 1]];
}
const [firstName, lastName] = splitName("Ada Lovelace");
console.log(`${lastName}, ${firstName}`);The return annotation guarantees that the function returns two strings. The labels first and last document the positions, but they do not create separate property names.
Tuple or ordinary array?
Use an ordinary array when every element has the same role and the length can vary:
const scores: number[] = [90, 85, 72];Use a tuple when position gives an element its meaning and the number of positions is part of the contract:
const rgb: [red: number, green: number, blue: number] = [255, 128, 0];| Type | Meaning |
|---|---|
| `number[]` | Any number of numbers |
| `[number, number]` | Exactly two numbers |
| `[string, number]` | Exactly two values with different positions |
Exercise
What is wrong with const result: [string, number] = [200, "OK"];?
Show answer
The values are in the wrong order. The first position must contain a string, and the second must contain a number.