← Back to TypeScript Course | Chapter 2: Basic Types | Lesson 3 of 11

Tuple Types

A tuple is an array with a fixed number of elements and known types at specific positions. Tuples are useful when each position in a small collection has a different meaning.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.