0
0
Typescriptprogramming~5 mins

Optional elements in tuples in Typescript

Choose your learning style9 modes available
Introduction

Optional elements in tuples let you create fixed-size lists where some items can be left out. This helps when you want to allow some parts to be missing but keep the order.

When you want to represent a fixed list of values but some values might not always be there.
When defining function parameters that accept a fixed number of arguments but some are optional.
When working with data where some fields are sometimes missing but the order matters.
Syntax
Typescript
type MyTuple = [string, number?, boolean?];

Use a question mark ? after the type to mark an element as optional.

Optional elements must come after required elements in the tuple.

Examples
This tuple has one required string and two optional elements: a number and a boolean.
Typescript
type PersonInfo = [string, number?, boolean?];

const a: PersonInfo = ["Alice"];
const b: PersonInfo = ["Bob", 30];
const c: PersonInfo = ["Carol", 25, true];
Here, the third coordinate is optional, so you can have 2D or 3D points.
Typescript
type Coordinates = [number, number, number?];

const point1: Coordinates = [10, 20];
const point2: Coordinates = [10, 20, 30];
Sample Program

This program defines a tuple with optional elements and prints each part, showing how missing values are handled.

Typescript
type User = [string, number?, boolean?];

function printUser(user: User) {
  const [name, age, isAdmin] = user;
  console.log(`Name: ${name}`);
  if (age !== undefined) {
    console.log(`Age: ${age}`);
  } else {
    console.log("Age: not provided");
  }
  if (isAdmin !== undefined) {
    console.log(`Admin: ${isAdmin}`);
  } else {
    console.log("Admin: not provided");
  }
}

printUser(["Alice"]);
printUser(["Bob", 28]);
printUser(["Carol", 35, true]);
OutputSuccess
Important Notes

Optional elements must be at the end of the tuple; you cannot have a required element after an optional one.

When accessing optional elements, check if they are undefined to avoid errors.

Summary

Optional elements in tuples let you have fixed order but allow some items to be missing.

Mark optional elements with ? after the type.

Always put optional elements after required ones.