Advertisement
Intermediate TypeScript, Primitive Types, Arrays & Tuples

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.

Save TypeScript mock interview
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 included
Real-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