TypeScript ยท Chapter 8 of 44

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.

Syntax
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.

Example 1 (typescript)
let user: [string, number] = ["Alice", 30];
console.log(`${user[0]} is ${user[1]} years old`);
Output
Alice is 30 years old

The tuple guarantees the first element is a string and the second is a number.

Example 2 (typescript)
let point: [number, number] = [3, 4];
const [x, y] = point;
console.log(x + y);
Output
7

Tuples 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.
๐Ÿ’ก Note: Use tuples for small, fixed groupings of related but differently-typed values, such as coordinate pairs.

๐Ÿ“ Quick Quiz

1. What makes a tuple different from a regular array?

2. Which is a valid tuple type for a name and age?

3. In `let point: [number, number] = [3, 4];`, what is point[0]?