Tuples

What is a Tuple?

A tuple is an array with a fixed length where each position has its own type. [string, number] means "exactly two elements: first a string, then a number".

Example

const item: [string, number] = ["Basmati Rice", 120];
const [name, price] = item; // destructuring keeps the types

console.log(name.toUpperCase(), price * 2);

function minMax(values: number[]): [number, number] {
  return [Math.min(...values), Math.max(...values)];
}
const [low, high] = minMax([499, 89, 1299, 250]);
console.log("low:", low, "high:", high);

Output

BASMATI RICE 240
low: 89 high: 1299

Tuple Mistakes

Example

Wrong order (TS2322) and reading a position that does not exist (TS2493) are both errors.

const item: [string, number] = [120, "Basmati Rice"];
const pair: [string, number] = ["Pen", 20];
console.log(pair[2]);

Compiler output (tsc)

Line 1: error TS2322: Type 'number' is not assignable to type 'string'.
Line 1: error TS2322: Type 'string' is not assignable to type 'number'.
Line 3: error TS2493: Tuple type '[string, number]' of length '2' has no element at index '2'.

Tip: React hooks use tuples: const [count, setCount] = useState(0) returns a [number, Dispatch] tuple.