Course contentsShow
← TypeScript
Lesson 120 of 1,7963. Basic TypesFree lesson

Optional Tuple Elements

Mark tuple positions as optional with ? to allow shorter tuples: [string, number?] accepts one or two elements.

Optional Tuple Elements

What you'll learn: How to make some positions in a tuple optional so it can accept fewer elements than its full length.

The Core Idea

So far, you've worked with tuples where every position must be filled. But sometimes you want flexibility — where certain elements might or might not be present. TypeScript lets you mark tuple positions as optional using the ? symbol, just like with object properties.

Think of it like a form where some fields are required and others are optional. A tuple with optional elements works the same way: the first elements might be mandatory, but later ones can be skipped.

How It Works

You add ? after the type of any position you want to make optional:

let user: [string, number?];

user = ["Alice"];           // Valid: name only
user = ["Bob", 42];         // Valid: name and age

In this example, the second element (a number) is optional. You can create a tuple with just the name, or include the age if you have it.

Important rules:

  • Optional elements must come after required ones
  • Once you make an element optional, all elements after it must also be optional or rest elements
// Valid patterns
let coord: [number, number, number?];          // z is optional
let person: [string, number?, boolean?];       // age and active both optional

// Invalid pattern
// let broken: [string?, number];  // ❌ Required after optional

Practical Use

Optional tuple elements are perfect for functions that return varying amounts of data:

function parseInput(input: string): [string, number?] {
  const parts = input.split(":");
  if (parts.length === 1) return [parts[0]];
  return [parts[0], parseInt(parts[1])];
}

Key Takeaway: Use ? after a tuple element's type to make that position optional, allowing tuples of different valid lengths while maintaining type safety for each position.