Sub topic 9
Optional and Rest Elements in Tuples
This chapter assumes you can write basic tuple types such as [number, string] and destructure them. It also assumes you know union types and how undefined behaves in TypeScript. By the end you will be able to write tuples whose length varies, predict the types TypeScript produces for them, and avoid the common errors.
Why fixed-length tuples are not always enough
A plain tuple such as [number, number] accepts exactly two elements. Real data often varies. A range might have an end or not. A database row might have an id followed by any number of tags. TypeScript handles both cases with two tuple features:
- An optional element, written with
?after the type. - A rest element, written with
...before an array type.
Both keep the type of each known position, so you keep more precision than a plain array gives you.
Optional elements
Put ? after an element's type to mark it optional. The element may be missing, and when it is present it must have the declared type.
type Range = [start: number, end?: number];
const r1: Range = [0];
const r2: Range = [0, 10];
// const r3: Range = []; // Error: Source has 0 element(s) but target requires 1.
// const r4: Range = [0, 10, 20]; // Error: Source has 3 element(s) but target allows only 2.
function describe(range: Range): string {
const [start, end] = range;
return end === undefined ? `from ${start}` : `${start} to ${end}`;
}
console.log(describe(r1)); // from 0
console.log(describe(r2)); // 0 to 10Reading an optional element gives you T | undefined. In describe, end has type number | undefined, so you have to handle undefined before using it as a number.
Rules for optional elements
- Optional elements must come after all required elements.
[a?: number, b: string]is an error. - Once an element is optional, every element after it must also be optional (or be a rest element).
- The tuple's
lengthbecomes a union of the possible lengths. For[number, string?],lengthhas type1 | 2.
type Pair = [number, string?];
function lengthOf(p: Pair): 1 | 2 {
return p.length; // length is typed as 1 | 2
}
function show(p: Pair): string {
if (p.length === 2) {
return `${p[0]}:${p[1].toUpperCase()}`; // p is narrowed to [number, string]
}
return `${p[0]}`;
}Checking length narrows the tuple. This works because length is a union of literal types, so TypeScript can discriminate on it.
Optional versus `| undefined`
An optional element is not the same as an element whose type includes undefined.
type A = [number, string?];
type B = [number, string | undefined];
const a: A = [1]; // OK: element can be absent
// const b: B = [1]; // Error: B requires two elements
const b: B = [1, undefined]; // OK: element must be present, value may be undefinedUse ? when the caller may leave the position out. Use | undefined when the position must always exist but may hold no value.
The exactOptionalPropertyTypes compiler option affects optional tuple elements as well. With it on, an optional element rejects an explicit undefined unless the element type includes undefined. Without it, [number, string?] accepts [1, undefined].
Rest elements
A rest element uses ... followed by an array type. It stands for zero or more elements of that type.
type Row = [id: number, ...tags: string[]];
const row1: Row = [1];
const row2: Row = [2, "new"];
const row3: Row = [3, "new", "urgent"];
// const bad: Row = ["x", "new"]; // Error: Type 'string' is not assignable to type 'number'.
function formatRow([id, ...tags]: Row): string {
return `#${id} [${tags.join(", ")}]`;
}
console.log(formatRow(row3)); // #3 [new, urgent]The first position is a required number. After it, any number of strings is allowed. In the destructuring pattern, tags has type string[].
Where a rest element can go
A rest element does not have to be last. It can sit in the middle or at the start, provided there is only one and no optional element follows it.
type StartRest = [...names: string[], total: number];
type MiddleRest = [first: boolean, ...middle: number[], last: string];
const s1: StartRest = [5];
const s2: StartRest = ["a", "b", 3];
const m1: MiddleRest = [true, "end"];
const m2: MiddleRest = [false, 1, 2, 3, "end"];Elements after a rest element are matched from the end of the array. When you assign a value, TypeScript treats the final items as the trailing positions and everything between as the rest.
Rules for rest elements
- A tuple can have at most one rest element.
- A rest element cannot be followed by an optional element.
- The rest element's type must be an array type (or a tuple type, which is covered in the variadic chapter).
- A tuple with a rest element has
lengthof typenumber, since the length is unbounded.
Combining optional and rest
Optional elements may precede a rest element. This gives you a required prefix, an optional middle, and a variable tail.
type Args = [required: string, optional?: number, ...rest: boolean[]];
const x1: Args = ["a"];
const x2: Args = ["a", 1];
const x3: Args = ["a", 1, true, false];
// const x4: Args = ["a", true]; // Error: Type 'boolean' is not assignable to type 'number'.Note that you cannot skip the optional element to supply the rest. To provide any boolean, you must provide the number first.
How inference treats these tuples
TypeScript does not infer optional or rest tuples from plain array literals. A literal like [1, "a"] is inferred as (string | number)[]. You get a tuple only when you annotate, use as const, or the context expects one.
const inferred = [1, "a"]; // (string | number)[]
const annotated: [number, string?] = [1];
const fromContext: Range = [0, 5]; // contextual typing applies the tuple typeWhen a function parameter has a tuple type, an array literal passed to it is checked against that tuple, so you do not need to annotate at the call site.
function setRange(range: [start: number, end?: number]): void {
console.log(range);
}
setRange([1]);
setRange([1, 5]);Assignability between tuple shapes
Tuples with optional and rest elements follow predictable assignability rules. A shorter or more specific tuple can be assigned to a more flexible one, but not the other way round.
let fixed: [number, string] = [1, "a"];
let flexible: [number, string?] = [1];
let variable: [number, ...string[]] = [1];
flexible = fixed; // OK: [number, string] fits [number, string?]
variable = fixed; // OK: one string fits ...string[]
// fixed = flexible; // Error: source may have fewer elements
// fixed = variable; // Error: source may have a different lengthThe assignment direction follows one rule: the target must accept every value the source could hold. A tuple with a possibly missing element cannot satisfy a target that demands it.
Common errors
| Mistake | What happens | Fix | Column |
|---|---|---|---|
| Required element after an optional one | Compile error: a required element cannot follow an optional element | Make the later element optional, or reorder | |
| Two rest elements | Compile error: a rest element cannot follow another rest element | Use one rest element, or restructure with a union of tuples | |
| Using an optional element without checking | `T \ | undefined` is not assignable to `T` | Narrow with `=== undefined` or check `length` |
| Expecting `[1, "a"]` to infer as a tuple | It infers as `(string \ | number)[]` | Annotate the variable or use `as const` |
| Using `?` when the value must exist | Callers can omit it | Use `T \ | undefined` instead |
Choosing a design
For a small, known maximum, optional elements document the shape clearly and give you a narrowable length. For an open-ended tail, use a rest element. If the variation is not just at the end, a union of tuples is often clearer than a clever combination:
type Result = [ok: true, value: string] | [ok: false, error: Error];
function handle(r: Result): string {
if (r[0]) {
return r[1]; // narrowed to string
}
return r[1].message; // narrowed to Error
}The first element is a literal type, so checking it narrows the whole tuple.
Exercise
Given type Cfg = [name: string, port?: number, ...flags: boolean[]], which of these are valid: ["a"], ["a", true], ["a", 80, true, false], [80, "a"]? Explain each.
Show answer
["a"] is valid, because only name is required. ["a", true] is invalid, because the second position is port?: number, and a boolean cannot skip it to reach the rest elements. ["a", 80, true, false] is valid: name, port, then two flags. [80, "a"] is invalid, because the first element must be a string.
Exercise
Write a type Log for tuples that start with a required level of type "info" | "warn" | "error" and are followed by any number of string messages. Then write a function format(log: Log): string that joins the messages with a space and prefixes the level in upper case.
Show answer
type Log = [level: "info" | "warn" | "error", ...messages: string[]];
function format([level, ...messages]: Log): string {
return ${level.toUpperCase()}: ${messages.join(" ")};
}
format(["warn", "disk", "almost", "full"]); // "WARN: disk almost full"