Sub topic 3
Optional and Rest Elements in Tuples
Assume you know JavaScript arrays, basic TypeScript annotations, and union types. A tuple describes an array with a known length and a specific type at each position.
Optional and rest elements
Use ? for an optional position. Optional elements must come after required elements. Use ... for a rest element that accepts zero or more values. A rest element must be last.
type Range = [start: number, end?: number];
type TaggedRow = [id: number, ...tags: string[]];
const onePoint: Range = [10];
const interval: Range = [10, 20];
const row: TaggedRow = [1, "new", "urgent"];
console.log(onePoint, interval, row);The type of end is number | undefined when it is read. The rest part behaves like an array of its element type.
Labeled tuple elements
Labels document the meaning of positions:
type UserEntry = [name: string, active: boolean];
const entry: UserEntry = ["Ada", true];Labels do not create property names. You still access values by index or destructure them.
Readonly tuples and `as const`
A readonly tuple prevents mutation through that reference. as const makes a literal deeply readonly and preserves its exact positions and values.
const point = [10, 20] as const;
// point: readonly [10, 20]
function showPoint(value: readonly [number, number]): void {
console.log(value[0], value[1]);
}
showPoint(point);Use readonly tuples for fixed data that callers should not change.
> callout note > readonly protects the reference used by the function. It does not freeze every other reference to the same underlying object at runtime.
Tuple pitfalls
A mutable tuple does not fully enforce its length during mutation:
const pair: [number, string] = [1, "a"];
pair.push(3); // Allowed: push accepts number | string
// pair[2]; // Error: no element exists at index 2Prefer readonly tuples when length must remain stable.
Tuples as parameter lists
Parameters extracts a function's parameters as a tuple. A tuple can then be spread into the call.
function connect(host: string, port: number): string {
return `${host}:${port}`;
}
type ConnectArgs = Parameters<typeof connect>;
const args: ConnectArgs = ["localhost", 8080];
console.log(connect(...args));Variadic tuple types
Variadic tuples combine tuple types while preserving their positions:
function concat<T extends unknown[], U extends unknown[]>(
first: T,
second: U
): [...T, ...U] {
return [...first, ...second];
}
const result = concat([1, "a"] as [number, string], [true] as [boolean]);
// result: [number, string, boolean]
console.log(result);Exercise
What tuple type accepts a required string followed by any number of booleans?
Show answer
[name: string, ...flags: boolean[]].