Optional and rest tuple elements
Concept and syntax
An optional tuple element label?: string may be omitted, so reading it can return undefined. A rest element ...extras: number[] permits a variable number of numeric elements after fixed positions. Use a fixed leading element to require a minimum shape. Optional elements and rest elements affect static positions and permitted lengths, not runtime validation.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
const pair: [count: number, label?: string] = [3];const values: [first: string, ...extras: number[]] = ["tea", 2, 4];console.log(pair[1] === undefined, values.length);Expected output (one line per log):
true 3Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
const values: [first: string, ...extras: number[]] = ["tea", "bad"];Expected compiler diagnostic: TS2322. The rest positions accept numbers only. Use a number or omit the extra element.
Practice and recap
Try a tuple containing only the required first element, then one with three numeric extras. Read an omitted optional position.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Optional and rest tuple elements — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Which element can be omitted in [count: number, label?: string]?
What does ...extras: number[] permit?
Which initializer matches the required first and rest element types?
const values: [first: string, ...extras: number[]] = ["tea", "bad"];