Sub topic 9
Optional and Rest Elements in Tuples
This chapter assumes basic JavaScript arrays, TypeScript annotations, and union types. It also assumes you know that a tuple records the type of each position, while an array records one element type for any number of positions.
Optional tuple elements
An optional tuple element may be present or omitted. Add ? to its type:
type Range = [start: number, end?: number];
const point: Range = [10];
const interval: Range = [10, 20];
function describeRange(range: Range): string {
const [start, end] = range;
if (end === undefined) {
return `Starting at ${start}`;
}
return `From ${start} to ${end}`;
}
console.log(describeRange(point));
console.log(describeRange(interval));The end position has the type number | undefined when read. Code must handle the case where the caller omitted it.
An optional element must come after all required elements. This would be invalid because TypeScript could not tell whether the first value belongs to the optional or required position:
// type Invalid = [first?: string, second: number];A tuple can have several optional elements:
type RequestOptions = [url: string, method?: string, timeoutMs?: number];
const request: RequestOptions = ["/users"];
const customRequest: RequestOptions = ["/users", "POST", 5000];Rest elements
A rest element represents zero or more values of one type. Write it with ...:
type TaggedRow = [id: number, ...tags: string[]];
const row: TaggedRow = [42];
const taggedRow: TaggedRow = [42, "new", "urgent"];
function formatRow(row: TaggedRow): string {
const [id, ...tags] = row;
return tags.length === 0
? `Row ${id}`
: `Row ${id}: ${tags.join(", ")}`;
}
console.log(formatRow(row));
console.log(formatRow(taggedRow));The first element is always a number. Every remaining element is a string. A rest element may contain no values, so [42] is valid.
A rest element must be an array type, such as string[] or boolean[]. It cannot be a single value:
// type Invalid = [number, ...string];Optional elements cannot follow a rest element. Required elements after a rest element are possible in some tuple designs, but they can make calls and destructuring harder to understand. Keep the rest element at the end unless a leading or middle rest pattern clearly improves the API.
Choosing optional or rest
Use an optional element when a particular position has a known meaning but may be omitted. Use a rest element when the tuple has a fixed beginning or ending followed by a variable number of values.
| Need | Tuple design |
|---|---|
| A possibly omitted second coordinate | `[x: number, y?: number]` |
| An identifier followed by labels | `[id: number, ...labels: string[]]` |
| Several values with no position meaning | `string[]` |
Common errors
Do not replace a rest tuple with a broad union array when position matters. [number, ...string[]] guarantees that the first value is numeric. (number | string)[] does not.
Also remember that optional values are not automatically safe to use. Check for undefined before calling a method or performing arithmetic on them.
Exercise
What values are valid for type Event = [name: string, ...codes: number[]]?
Show answer
["ready"], ["ready", 200], and ["ready", 200, 201] are valid. The first value must be a string, and every later value must be a number.