Codectionary / Developer documentation / TypeScript

Labeled Tuples and Optional Elements

A tuple describes positions with different meanings and possibly different types.

What it is and why to use it

A tuple describes positions with different meanings and possibly different types. Labels improve editor hints, and an optional trailing element describes an omitted value without changing the required positions. This is useful for small fixed-format values such as coordinates.

Common mistakes and limitations

Do not confuse tuple labels with runtime object keys. Optional positional elements must respect tuple ordering rules. Readonly tuples are a separate choice when mutation should be restricted.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

type Point = [x: number, y: number, label?: string];

Examples

Labeled Tuples and Optional Elements

Standalone TypeScript 5.8+ example; expected output is explained below.

type Point = [x: number, y: number, label?: string];
function describe([x, y, label = "Point"]: Point): string {
  return label + ": " + x + "," + y;
}
console.log(describe([2, 5]));
console.log(describe([2, 5, "Start"]));
  1. x and y occupy required numeric positions; label is the optional third position.
  2. Destructuring reads the positions and supplies Point when the third value is undefined.
  3. Labels aid tooling but do not create named properties such as point.x. An object is often clearer if the data gains many fields.
  4. Expected output: Point: 2,5 Start: 2,5

Best practices

  • Do not confuse tuple labels with runtime object keys. Optional positional elements must respect tuple ordering rules. Readonly tuples are a separate choice when mutation should be restricted.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading