Tuple Types
In this page:
Basic Tuple
A tuple type defines the exact type of each position in a fixed-length array, such as [string, number] for a name paired with an age. Unlike a regular array type, the order and count of the types matters, not just which types are allowed somewhere in the collection.
Example: Basic Tuple
let person: [string, number] = ["Aisha", 30];
console.log(person);
Accessing Tuple Values
Tuple elements can be accessed using their numeric indexes just like a regular array, but TypeScript already knows the specific type expected at each position. This means tuple[0] is known to be a string and tuple[1] a number, without any manual casting.
Example: Accessing Tuple Values
let person: [string, number] = ["Kiran", 28];
console.log(person[0], person[1]);
Tuple Destructuring
Tuple values can be unpacked into separate named variables using array destructuring, for example const [name, age] = person. The types of the resulting variables are automatically inferred from their corresponding tuple positions.
Example: Tuple Destructuring
const person: [string, number] = ["Divya", 22];
const [name, age] = person;
console.log(name, age);
Optional Tuple Elements
Tuple elements can be marked optional by adding a question mark after their type, such as [string, number?]. Optional elements must always come after every required element, since their position still has to be predictable.
Example: Optional Tuple Elements
let entry: [string, number?] = ["Rahul"];
console.log(entry);
entry = ["Meera", 5];
console.log(entry);
Readonly Tuples
A readonly tuple, written as readonly [string, number], prevents any element from being reassigned after the tuple is created. This is useful for representing a fixed, immutable pairing of values, like a coordinate that should never be mutated in place.
Example: Readonly Tuples
let point: readonly [number, number] = [10, 20];
// point[0] = 99; // rejected: readonly tuples block reassignment
console.log(point);
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: