Optional Tuple Elements
What you'll learn: How to declare tuple elements that may or may not be present using the ? modifier, and understand how this affects type safety.
What Are Optional Tuple Elements?
Just as object properties and function parameters can be optional, tuple elements can also be optional. When you mark a tuple element with ?, TypeScript understands that the value at that position might be present or might be undefined.
Think of it like a recipe that requires eggs and flour, but sugar is optional. The recipe still works whether or not you include sugar — TypeScript's optional tuple elements work the same way.
Declaring Optional Elements
You add the ? modifier directly after the type of any tuple element:
type Coordinates = [number, number, number?];
const point2D: Coordinates = [10, 20]; // Valid
const point3D: Coordinates = [10, 20, 30]; // Also valid
In this example, the third element (the z-coordinate) is optional. Both 2D and 3D points are valid Coordinates tuples.
Type Implications
When you access an optional tuple element, TypeScript infers its type as T | undefined:
type Response = [number, string?];
const res: Response = [200];
const code = res[0]; // Type: number
const message = res[1]; // Type: string | undefined
Notice that res[1] has the type string | undefined, not just string. TypeScript forces you to handle the possibility that the element might not exist.
Placement Rules
Optional elements must come after all required elements — just like optional function parameters:
type Valid = [string, number?]; // ✓ OK
type Invalid = [string?, number]; // ✗ Error!
You can have multiple optional elements in a row:
type FlexibleTuple = [string, number?, boolean?];
Key Takeaway: Optional tuple elements use ? to mark positions that may contain undefined, enabling tuples of varying lengths while maintaining type safety. They must always appear after required elements, and their type becomes a union with undefined.