TS Tuples
A tuple is an array with a known length and a known type at each position. Great for fixed-shape records — coordinates, RGB triples, a function returning two values.
Basics
TS
type Point = [number, number]; const origin: Point = [0, 0]; const [x, y] = origin; // destructured
Named tuple elements (4.0+)
TS
type Point = [x: number, y: number]; type RGB = [red: number, green: number, blue: number]; // Editors show "x" and "y" in hints — much friendlier than "arg_0".
Optional & rest elements
TS
type Optional = [string, number?]; const a: Optional = ['hi']; const b: Optional = ['hi', 42]; type Variadic = [first: string, ...rest: number[]]; const v: Variadic = ['hi', 1, 2, 3];
Readonly tuples
TS
const rgb: readonly [number, number, number] = [255, 128, 0]; // rgb[0] = 0; // ✗ error
const assertion → tuple
Without as const, TS widens an array literal to T[]:
TS
const a = ['ok', 42]; // (string | number)[] const b = ['ok', 42] as const; // readonly ['ok', 42]
Tuples for "return many values"
TS
function minMax(nums: number[]): [number, number] {
return [Math.min(...nums), Math.max(...nums)];
}
const [lo, hi] = minMax([3, 1, 4, 1, 5]);
Tip: If a "return two values" function grows beyond 2-3 fields, switch to an object — names beat positions for clarity. Save tuples for genuinely positional data (point, color, time range).
Example
Example
type Point = [x: number, y: number]; const origin: Point = [0, 0]; const [x, y] = origin; console.log(x, y); // Readonly tuple const rgb: readonly [number, number, number] = [255, 128, 0];Try it Yourself »
Exercise
Two-number tuple for a 2D point.
const p:
= [3, 4];
Square brackets enclosing two number entries.
Discussion
Loading…