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

Readonly Tuples

Use readonly modifier to prevent modification: readonly [string, number] disallows push, pop, and index assignment.

What You'll Learn

You'll discover how to protect tuples from accidental modification by marking them as readonly, preventing methods like push, pop, and direct index reassignment.


Why Readonly Tuples Matter

Sometimes you create a tuple to represent a fixed structure—like a coordinate [x, y] or a database row. You want to read those values, but never accidentally change them. TypeScript's readonly modifier locks down your tuple so it can't be mutated.

The Core Idea

When you prefix a tuple type with readonly, TypeScript prevents:

  • Index assignment: You can't do point[0] = 10
  • Array mutation methods: No push, pop, shift, unshift, splice, etc.
  • Reassigning the whole tuple (you still can't if it's declared with const)

Think of it like sealing an envelope. You can read what's inside, but you can't change the contents.

Syntax

const point: readonly [number, number] = [3, 5];

// ✅ Reading is fine
console.log(point[0]); // 3

// ❌ These all cause errors:
point[0] = 10;        // Cannot assign to '0' because it is a read-only property
point.push(7);        // Property 'push' does not exist on type 'readonly [number, number]'
point.pop();          // Property 'pop' does not exist on type 'readonly [number, number]'

When to Use Readonly Tuples

Use readonly tuples when:

  • The data represents an immutable fact (coordinates, RGB colors, dates)
  • You want to prevent accidental mutations in shared code
  • You're returning structured data that shouldn't be changed by the caller

Key Takeaway: The readonly modifier transforms tuples into immutable structures—you can read elements but cannot modify them through index assignment or array methods, ensuring data integrity.