Thuta Learning
TypeScript
IntermediateProgrammingIntermediate

Tuples

TypeScriptLesson 1120 min

What you'll walk away with

  • Explain how a tuple type differs from an array type
  • Return two values from a function as a tuple and destructure them
  • Write labeled, optional (?) and rest (...) tuple elements
  • Close the push() loophole of mutable tuples with readonly

Explain it simply

Explain it simply

Think of a map location written as two numbers, latitude and longitude. There are always exactly two, and the order matters: swap them and you land in another country. A tuple is for short lists like this, where the count is fixed and every position has its own meaning.

The tuple type [number, string] says "two elements: a number first, then a string". A plain array only knows one element type and never knows how many elements there are.

Problem → Why → Solution

The problem: a returned array forgets its positions

Suppose you write a function that splits a CSV line such as "Mya, 42" into a name and a score, returning both values in an array. Without a return type, TypeScript infers (string | number)[] and the knowledge of which position holds what is lost. As a result you cannot call points.toFixed(), because the compiler thinks points might be a string.

scores.ts
function parseEntry(line: string) {
  const [name, raw] = line.split(",");
  return [name.trim(), Number(raw)]; // inferred: (string | number)[]
}

const [player, points] = parseEntry("Mya, 42");
points.toFixed(0);
// Error: Property 'toFixed' does not exist on type 'string | number'.

Why does this happen?

By default TypeScript infers an array literal as an array type, because you might push to it later. To keep per-position types, write the return type yourself as [string, number]. Then player is a string, points is a number, and returning the two values in the wrong order becomes a compile error.

Core concept: a type for every position

A tuple type is written [Type1, Type2, ...]. It knows two things: how many elements there are, and which type sits at each position. With let user: [number, string], user[0] is a number, user[1] is a string, and reading user[2] gives "Tuple type '[number, string]' of length '2' has no element at index '2'". Putting the values in the wrong order, as in ["Steve", 1], is an error too.

Tuples pair naturally with destructuring. Writing const [id, name] = user; gives id the type number and name the type string, and you can choose any variable names. React's useState() uses exactly this pattern: in const [count, setCount] = useState(0); the value and its setter come back as a tuple.

Watch out: TypeScript does not infer a tuple from an array literal on its own. const pair = [1, "a"]; is (string | number)[]. There are three ways to get a tuple: annotate the variable, write the function's return type, or add as const (which also gives literal types, readonly [1, "a"]).

At runtime a tuple is just an ordinary JavaScript array, and nothing guards its length. That is why the compiler still allows push() on a mutable tuple as long as the value matches one of the element types. Close this loophole with a readonly tuple such as readonly [number, string].

So when do you pick a tuple over an object? Ask whether the values are told apart by position or by name. For two or three values with a natural order, like [x, y], a tuple is short and clear. When there are more values, or the order means nothing, an object such as { id, name, email } is safer, because each property name explains itself.

number[][number, string]
Lengthanyalways 2
Element typesall the samediffer by position
Reading index 5number (may be undefined)compile error
Mental model: numbered slots
  1. A fixed number of slots
  2. Every slot has its own type
  3. Destructuring keeps each type
  4. readonly stops extra slots

An array says "many things of this kind"; a tuple says "exactly these things, in this order".

General pattern

typescript
let pair: [TypeA, TypeB] = [a, b];
const [first, second] = pair;            // first: TypeA, second: TypeB

type Labeled = [label: TypeA, other: TypeB];
type WithOptional = [TypeA, TypeB?];
type WithRest = [TypeA, ...TypeB[]];
type Fixed = readonly [TypeA, TypeB];

function name(): [TypeA, TypeB] { return [a, b]; }

List the type of each position in order inside square brackets. Labels are documentation only, ? makes a trailing element optional, and ... describes an open-ended tail.

Example: a [number, string] tuple

This example declares a tuple variable first and assigns it afterwards. The commented-out line shows what happens when the order is reversed. Uncomment it to see the error yourself, then try reading user[2] to see the length error as well.

typescript
// Declare a tuple type
let user: [number, string];

// Initialize it
user = [1, "Steve"];

// user = ["Steve", 1]; // Error: Type 'string' is not assignable to type 'number'.

console.log(user[1]);

Code breakdown

  1. Line 2let user: [number, string];

    user must be a two-element tuple: a number (the id) at position 0 and a string (the name) at position 1.

  2. Line 5user = [1, "Steve"];

    Both values are in the right positions, so this is accepted. [1] or [1, "Steve", true] would fail because the length does not match.

  3. Line 7// user = ["Steve", 1];

    Uncommented, this gives "Type 'string' is not assignable to type 'number'" because a string is at position 0. A plain (string | number)[] array could not catch this mistake.

  4. Line 9console.log(user[1]);

    The compiler knows user[1] is a string, so user[1].toUpperCase() would be safe too. The output is Steve.

You should see
Steve

Labeled, optional and rest elements

The labels in [name: string, score: number] appear in editor hovers and error messages, making the tuple easier to read, but they do not force the names you destructure into. An optional element such as end?: number can only appear at the end, and a rest element such as ...details: string[] means "any number of strings after the first element". In the code below, notice that parseEntry() now has an explicit Entry return type, which fixes the problem from the start of the lesson: points is a number again, so points + 8 is real addition.

tuple-forms.ts
type Entry = [name: string, score: number];

function parseEntry(line: string): Entry {
  const [name, raw] = line.split(",");
  return [name.trim(), Number(raw)];
}

const [player, points] = parseEntry("Mya, 42");
console.log(player.toUpperCase(), points + 8);

type Span = readonly [start: number, end?: number];
const fromFive: Span = [5];
const fiveToNine: Span = [5, 9];
console.log(fromFive.length, fiveToNine.length);

type LogLine = [level: string, ...details: string[]];
const line: LogLine = ["warn", "disk", "85%"];
console.log(line[0], line.slice(1).join(" "));

In real projects

Where this shows up in real projects

The tuples you meet most often live in React hooks: useState() returns [value, setValue], and many custom hooks return tuples such as [data, error] or [isOpen, toggle]. Because they are tuples, callers can name the variables whatever they like; with an object they would have to rename properties.

Other common uses are coordinates like [latitude, longitude], colours like [r, g, b], the [key, value] pairs returned by Object.entries(), and CSV rows. Promise.all() is typed with tuples too: in const [user, orders] = await Promise.all([loadUser(), loadOrders()]); each variable gets the type of its own promise's result. Once a record grows past three or four fields, teams switch from a tuple to an object: nobody remembers what row[3] means, but row.isActive explains itself.

Common mistakes

Common mistakes

1. Trusting the compiler to guard a mutable tuple's length

let t: [number, string] = [1, "a"]; t.push(2); compiles, and t.length becomes 3 while the type still claims two elements. If the tuple should not change, type it readonly [number, string], which removes push() entirely.

2. Expecting a tuple without writing the type

return [name, score]; on its own gives (string | number)[], so every destructured variable becomes a union. Write the return type : [string, number], or return the value with as const.

3. Using a tuple for a record with many fields

In a tuple like [string, string, number, boolean, string], positions are easy to mix up, and swapping the two strings is not even a compile error because their types match. Use an object type with named properties for data like this.

Best practices

Best practices

  • Use tuples for two or three values whose order is natural, such as coordinates or key-value pairs.
  • Add labels so each position explains itself: [lat: number, lng: number].
  • Make tuples returned from functions readonly when callers have no reason to change them.

Mini challenge

Mini challenge: colours and min/max

Write a function that turns an RGB colour tuple into a hex string, and another that returns the smallest and largest number of a list as a tuple.

  • The RGB type is a labeled readonly tuple [red, green, blue]
  • toHex([255, 136, 0]) returns "#ff8800"
  • minMax(values) returns a [min, max] tuple, or undefined for an empty list
  • Destructure minMax's result and print it
tuples-practice.ts
type RGB = /* TODO: labeled readonly tuple of three numbers */;

function toHex(color: RGB): string {
  // TODO: each channel -> 2 hex digits, prefixed with "#"
}

function minMax(values: readonly number[]) /* TODO: return type */ {
  // TODO: undefined for an empty list, otherwise [min, max]
}

// TODO: print toHex([255, 136, 0]) and the min/max of [7, 2, 9, 4] and []

Expected: It prints: #ff8800 min 2, max 9 no values

Show hint

c.toString(16).padStart(2, "0") turns a 0-255 number into two hex digits. Math.min(...values) and Math.max(...values) do the rest.

Show solution
tuples-practice.ts
type RGB = readonly [red: number, green: number, blue: number];

function toHex(color: RGB): string {
  return "#" + color.map((c) => c.toString(16).padStart(2, "0")).join("");
}

function minMax(values: readonly number[]): [min: number, max: number] | undefined {
  if (values.length === 0) return undefined;
  return [Math.min(...values), Math.max(...values)];
}

const brand: RGB = [255, 136, 0];
console.log(toHex(brand));

const result = minMax([7, 2, 9, 4]);
if (result) {
  const [low, high] = result;
  console.log(`min ${low}, max ${high}`);
}
console.log(minMax([]) ?? "no values");

Quick quiz 1 / 3

Without an annotation, what is the type of pair in const pair = [1, "a"];?

Quick quiz 2 / 3

What happens when you run let t: [number, string] = [1, "a"]; t.push(2); console.log(t.length);?

Quick quiz 3 / 3

Given type Span = [number, number?];, which value is NOT a valid Span?

What to remember

  • A tuple [A, B] is an array with a fixed length and its own type at each position.
  • Array literals do not become tuples on their own: use an annotation, a return type or as const.
  • Labels, ? and ... make tuples more readable and more flexible.
  • At runtime a tuple is a plain array, so close the push() loophole with readonly and use objects for records with many fields.

TypeScript Handbook — TypeScript

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Tuples | Thuta Learning