Sub topic 10
Labeled tuple elements
This chapter assumes you know tuple types, optional and rest elements in tuples, and destructuring. Labels add no new runtime behavior. They are names attached to tuple positions so that editors, error messages, and function signatures say what each position means.
Why labels exist
A tuple such as [number, number] tells you the length and the types, but not the meaning. Is it [x, y], [width, height], or [min, max]? Hovering over a function that returns a bare tuple gives you no hint. Labels fix this:
type Point = [x: number, y: number];
type Range = [start: number, end?: number];
type Row = [id: number, ...tags: string[]];
const p: Point = [10, 20];
const r: Range = [0];
const row: Row = [1, "new", "urgent"];
console.log(p, r, row);Each element gets a name followed by a colon and the type. Editors show these names in hovers and in signature help while you type a value.
Syntax rules
The label goes before the type, in the form name: Type. The other element kinds keep their usual markers, but the marker attaches to the label:
| Element kind | Unlabeled | Labeled |
|---|---|---|
| Required | `number` | `start: number` |
| Optional | `number?` | `end?: number` |
| Rest | `...string[]` | `...tags: string[]` |
Two details are easy to get wrong:
- For an optional element, the
?goes after the label, not after the type:end?: number. - For a rest element, the
...goes before the label, and the type must still be an array type:...tags: string[].
All or none
You cannot label only some of the elements. If any element has a label, every element needs one.
type Good = [id: number, name: string];
type AlsoGood = [number, string];
// type Bad = [id: number, string];
// Error: Tuple members must all have names or none of them can have names.The commented line shows the error. Pick one style per tuple type. If you add a label to one position, add one to the rest.
Labels are documentation only
Labels exist only in the type system. The compiler erases them, so the emitted JavaScript contains plain arrays. You also cannot read an element by its label.
type Point = [x: number, y: number];
const p: Point = [10, 20];
console.log(p[0]); // 10
// console.log(p.x); // Error: Property 'x' does not exist on type 'Point'.A tuple is still an array underneath, so you read elements by index or by destructuring. If you want property access by name, use an object type instead. The chapter on choosing between tuples and arrays covers when each fits.
Labels do not affect compatibility
Two tuple types with different labels but the same element types are interchangeable. The compiler compares lengths, optionality, and element types. It ignores names.
type Cartesian = [x: number, y: number];
type Polar = [radius: number, angle: number];
const c: Cartesian = [3, 4];
const polar: Polar = c; // compiles: labels are not compared
console.log(polar);This means a label cannot protect you from mixing up two tuples that mean different things. If Cartesian and Polar must stay distinct, tuples alone will not do that. You would need an object type or a branded type.
Labels and destructuring
The names you use when destructuring are independent of the labels. The labels do not create variables, and you may choose any local names:
type Range = [start: number, end: number];
function parseRange(text: string): Range {
const [a, b] = text.split("-").map(Number);
return [a, b];
}
const [from, to] = parseRange("3-9");
console.log(from, to); // 3 9Here start and end appear in the return type and in hovers, while the caller names the variables from and to. Keeping the local names close to the labels makes the code easier to read, but nothing enforces it.
A small caution about this example: with noUncheckedIndexedAccess enabled, destructuring the result of .map(Number) gives number | undefined for a and b, so the return line would fail to compile. Without that flag, as shown, it compiles. Chapter material on index access explains the flag.
Labels in function signatures
The most practical use of labels is in rest parameters typed as tuples. A tuple-typed rest parameter lets a function accept a fixed argument list, and the labels become the parameter names callers see.
function connect(...args: [host: string, port?: number]): string {
const [host, port = 80] = args;
return `${host}:${port}`;
}
console.log(connect("localhost")); // localhost:80
console.log(connect("localhost", 8080)); // localhost:8080To a caller, this function looks like connect(host: string, port?: number). Signature help shows host and port, not args_0 and args_1.
Without labels, the same signature would show generic names such as args_0. That is the main reason to label here.
Labels survive `Parameters<T>`
Parameters<T> returns a function's parameter list as a tuple, and it keeps the parameter names as labels. You can reuse that tuple to write a wrapper whose signature matches the original:
function log(
level: "info" | "warn",
message: string,
...details: unknown[]
): void {
console.log(`[${level}] ${message}`, ...details);
}
type LogArgs = Parameters<typeof log>;
// [level: "info" | "warn", message: string, ...details: unknown[]]
function logLater(...args: LogArgs): void {
setTimeout(() => log(...args), 0);
}
logLater("warn", "disk almost full", { freeMb: 120 });The wrapper logLater shows level, message, and details in the editor, even though you never wrote those names in its declaration. Writing the labels by hand on a tuple you expect to spread into a call has the same effect, which keeps wrappers readable.
Labels with generics and spreads
You can label the fixed positions around a generic tuple. This builds on the variadic tuple types introduced earlier:
function prepend<T extends unknown[]>(
id: number,
rest: T,
): [id: number, ...rest: T] {
return [id, ...rest];
}
const result = prepend(7, ["a", true]);
console.log(result); // [7, "a", true]The inferred type of result is [id: number, a: string, b: boolean]-style in spirit, but the compiler reports it as [id: number, string, boolean]-like output in some tooling versions, so do not depend on the exact text of hover output. Treat the displayed labels as a hint for people, never as something your code can check.
Common errors and gotchas
- Mixing labeled and unlabeled elements. This produces the "must all have names" error. Label every position or none.
- Putting
?on the type.[end: number?]is not valid. Write[end?: number]. - Expecting property access.
t.xdoes not work. Labels are not properties. - Expecting labels to prevent mix-ups. Tuples with different labels but the same shape are assignable to each other.
- Relying on hover text in tests or docs. The label text shown in tooling can change between TypeScript versions when types are combined or inferred. Your program's behavior never changes.
Choosing labels well
Good labels describe the role of the position, not its type. [start: number, end: number] says more than [first: number, second: number], and [id: number, ...tags: string[]] says more than [n: number, ...rest: string[]]. Because the compiler ignores labels, nothing checks them. A stale or misleading label is a documentation bug that will never fail a build, so keep labels accurate when you change a tuple's meaning.
Exercise
What is wrong with type Entry = [id: number, string, active?: boolean];, and how do you fix it?
Show answer
It mixes labeled and unlabeled elements, which TypeScript rejects with "Tuple members must all have names or none of them can have names." Label every element, for example type Entry = [id: number, name: string, active?: boolean];.
Exercise
Given type Cartesian = [x: number, y: number]; and type Polar = [radius: number, angle: number];, does const p: Polar = [3, 4] as Cartesian; compile? Explain why, and say how you would make the two types incompatible.
Show answer
Yes, it compiles. Tuple assignability compares length, optionality, and element types, and ignores labels, so both types are structurally [number, number]. To make them incompatible, use object types such as { x: number; y: number } and { radius: number; angle: number }, or add a brand property to each type.
Exercise
Write a function area that takes its two arguments as a labeled tuple rest parameter, so callers see the names width and height, and returns their product.
Show answer
function area(...args: [width: number, height: number]): number { const [width, height] = args; return width * height; }