Course outline · 0% complete

0/26 lessons0%

Course overview →

Tuples: Arrays with Fixed Positions

lesson 2-4 · ~10 min · 7/26

When each position means something

number[] says every element is a number, but nothing about how many elements there are or what each position means. Some data is positional by nature: a 2D point is exactly two numbers, x then y; a lookup result is a name and then a score. With a plain array type, swapping the two or adding a third slips through silently — the array type has no opinion about positions.

A tuple type fixes the length and gives each position its own type:

const point: [number, number] = [3, 7];
const entry: [string, number] = ["score", 42];

The compiler now enforces position: entry[0] is a string, entry[1] is a number, and entry[2] is an error because the tuple has exactly two slots. Compare (string | number)[], which allows any mix, any order, any length — the tuple is the stronger and more honest claim, and it is how a function can return two values at once with full checking.

Tuples pair naturally with destructuring: const [x, y] = point; declares x and y and fills them from positions 0 and 1, and each variable gets its positional type — here both are number.

Code exercise · typescript

Run it. The destructuring line unpacks point by position, so x and y are both typed number. Then try const [a, b, c] = point and run again — the tuple has no third slot, and the compiler says so.

Quiz

Why does const user: [string, number] = [36, "Ada"] fail to compile?

Code exercise · typescript

Your turn. Write minMax(nums: number[]): [number, number] that returns the smallest and largest value as one tuple. Start min and max at nums[0], update them in a single loop, then return [min, max]. Destructure the result into low and high and print the line shown.