Tuples

A fixed-length array where each position has its own type.

Syntaxlet pair: [string, number] = ["age", 30];

A tuple is an array with a fixed number of elements whose types are known for each position. It is perfect for pairing values of different types.

Example use

A coordinate might be [number, number], or a key/value pair might be [string, number].

Order matters — the first element must match the first type, the second the second type, and so on.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A coordinate system stores [latitude, longitude] as a [number, number] tuple ensuring the pair is never swapped.
  • A React hook returns [value, setValue] as a tuple so destructuring yields correctly typed variables.
  • A CSV parser returns [string, number, boolean] tuples representing typed row fields.

More examples

Basic tuple declaration

Declares fixed-position typed tuples and shows destructuring preserving per-position types.

Example · ts
const point: [number, number] = [51.5074, -0.1278]; // lat, lng
const entry: [string, number] = ['Alice', 42];

const [lat, lng] = point; // lat: number, lng: number

Tuple as function return

Mimics React's useState by returning a tuple so destructuring yields a typed value and a typed setter.

Example · ts
function useState<T>(initial: T): [T, (v: T) => void] {
  let state = initial;
  const set = (v: T) => { state = v; };
  return [state, set];
}

const [count, setCount] = useState(0); // count: number, setCount: (v: number) => void

Named tuple elements

Uses named tuple elements (TypeScript 4.0+) to label each position, making the tuple self-documenting.

Example · ts
type RGB = [red: number, green: number, blue: number];

const orange: RGB = [255, 165, 0];

function toHex([r, g, b]: RGB): string {
  return `#${r.toString(16)}${g.toString(16)}${b.toString(16)}`;
}

Discussion

  • Be the first to comment on this lesson.