Describing ShapesExtra· 30 min read

Tuples: Fixed-Length, Typed Lists

A tuple is an array with a fixed length where each position has its own type.

What you will learn

  • Define a tuple with typed positions
  • See how tuples differ from normal arrays
  • Use a realistic tuple example

An array where order and types are fixed

A normal array holds many values of one type. A tuple is special: it has a fixed number of items, and each position has its own type. The order matters.

A tuple with a string then a number
// [name, age] — position 0 is a string, position 1 is a number
let person: [string, number] = ['Asha', 21];

console.log(person[0].toUpperCase());  // string method, ok
console.log(person[1] + 1);            // number maths, ok

Note: Output: ASHA 22 TypeScript knows position 0 is a string and position 1 is a number, so it allows .toUpperCase() on the first and + 1 on the second.

Tuples catch wrong order and length

Order and length are enforced
let person: [string, number];

person = ['Asha', 21];   // correct
person = [21, 'Asha'];   // error — types are in the wrong order
person = ['Asha'];       // error — wrong length

Note: Output: Error: Type 'number' is not assignable to type 'string' (position 0). Error: Source has 1 element(s) but target requires 2. A tuple is strict: each slot must match its declared type, and the length must be exactly right.

A realistic use: a coordinate

Tuples shine for small fixed groups, like an (x, y) point or an RGB colour (RGB = the Red, Green and Blue amounts that make up a colour, e.g. [255, 0, 0] for red):

A Point tuple used in a function
type Point = [number, number];

function distanceFromOrigin(p: Point): number {
  return Math.sqrt(p[0] * p[0] + p[1] * p[1]);
}

console.log(distanceFromOrigin([3, 4]));

Note: Output: 5 The Point tuple guarantees exactly two numbers, so the maths is safe. (3, 4) is 5 units from the origin.

Tip: You meet tuples in real code: React's useState returns a tuple [value, setValue]. Knowing tuples helps you understand why const [count, setCount] = useState(0) works.

Watch out: Tuples are easy to misuse for big groups. If positions start meaning different things and the list grows, an object/interface with named properties is clearer than [string, number, boolean, number].

Q. How is a tuple different from a normal array?

Answer: A tuple fixes both the length and the type at each position, e.g. [string, number]. A normal array is a variable-length list of one type.

✍️ Practice

  1. Declare a tuple [string, boolean] for a setting like ["darkMode", true].
  2. Write a type RGB = [number, number, number] and create a colour value.

🏠 Homework

  1. Write a function that takes a [string, number] tuple of (product, price) and returns a formatted label, with its output.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →