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
- A labeled tuple documents what each position means.
- A rest element makes the tail variadic.
as conston an array literal produces a readonly tuple.
Keywords and builtins used here
EntryMathObjectasconstfunctionnumberreturnstringtype
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.
Step 3 of 5 in Functions & tuples, step 18 of 23 in Types & annotations.