typestar

Tuples in TypeScript

Fixed-length arrays with a type per position, and labeled elements.

type Point = [x: number, y: number];
type Entry = [key: string, value: number];
type Command = [name: string, ...args: string[]];

function distance([x1, y1]: Point, [x2, y2]: Point): number {
  return Math.hypot(x2 - x1, y2 - y1);
}

function run([name, ...args]: Command): string {
  return `${name}(${args.join(", ")})`;
}

const pair = [3, 4] as const;
const entries: Entry[] = Object.entries({ a: 1, b: 2 });

console.log(distance([0, 0], [3, 4]), run(["play", "go", "3"]));
console.log(pair.length, entries[0]?.[0]);

How it works

  1. A labeled tuple documents what each position means.
  2. A rest element makes the tail variadic.
  3. as const on an array literal produces a readonly tuple.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
518
Tokens
194
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 123 seconds.

Type this snippet

Step 3 of 5 in Functions & tuples, step 18 of 23 in Types & annotations.

← Previous Next →

Tuples in other languages