How do you make a tuple element optional, and how does that affect the tuple's minimum required length?
Short answer
Add '?' after a tuple element's type, similar to optional function parameters — optional elements must come after all required elements, and TypeScript correctly tracks that the tuple's minimum length no longer includes the optional trailing elements.
Advertisement
AModel answer
Add '?' after a tuple element's type, similar to optional function parameters — optional elements must come after all required elements, and TypeScript correctly tracks that the tuple's minimum length no longer includes the optional trailing elements.
type Point = [x: number, y: number, z?: number];
const p2d: Point = [3, 4]; // OK, z omitted
const p3d: Point = [3, 4, 5]; // OK, z includedReal-world example
Typing a 2D-or-3D coordinate tuple where the z-axis is only sometimes relevant.
Likely follow-ups
- Can you mix optional tuple elements with a rest element in the same tuple type?
Related topics