Course contentsShow
← TypeScript
Lesson 1374 of 1,79632. Advanced PatternsFree lesson

Accessing Tuple Elements by Index

Type-safe indexed access to tuple elements and how TypeScript tracks each position.

Accessing Tuple Elements by Index

What you'll learn: How TypeScript tracks the exact type of each position in a tuple and lets you access elements with complete type safety.

The Power of Position-Aware Types

Unlike arrays where every element has the same type, tuples in TypeScript remember the specific type at each position. When you access an element by its numeric index, TypeScript knows exactly what type you're getting—not just a union of all possible types.

Think of it like a form with labeled fields. If the form has a text field at position 0 and a checkbox at position 1, you know exactly what you're getting when you look at position 0 versus position 1. TypeScript brings this same precision to tuple access.

Index-Based Type Safety

// Define a tuple with specific types at each position
const user: [string, number, boolean] = ["Alice", 30, true];

// Access by index - TypeScript knows the exact type
const name = user[0];     // Type: string
const age = user[1];      // Type: number
const active = user[2];   // Type: boolean

// You get full autocomplete and type checking
const upperName = user[0].toUpperCase();  // ✓ Works
const nextAge = user[1] + 1;              // ✓ Works

Each index access gives you the precise type at that position, not a string | number | boolean union like an array would.

Out-of-Bounds Access

TypeScript tracks tuple length. Accessing beyond the defined positions gives you undefined:

const pair: [number, number] = [10, 20];

const first = pair[0];   // Type: number
const second = pair[1];  // Type: number
const third = pair[2];   // Type: undefined

Key Takeaway: TypeScript provides type-safe indexed access to tuples, remembering the exact type at each position and preventing out-of-bounds access with compile-time checks—giving you precision that arrays cannot match.