Course contentsShow
← TypeScript
Lesson 316 of 1,7967. ObjectsFree lesson

Readonly Index Signatures

Using readonly [key: string]: ValueType to prevent modification of dynamically keyed properties after object creation.

Readonly Index Signatures

What you'll learn: How to prevent modification of dynamically keyed properties by applying readonly to index signatures.

The Core Idea

Just like you can mark specific properties as readonly, you can also make all dynamically keyed properties read-only by placing readonly before an index signature. This prevents any modification to properties on an object after it's created, even when those property names aren't known in advance.

How It Works

The syntax combines two concepts you've already learned:

type Config = {
  readonly [key: string]: string;
};

const settings: Config = {
  theme: "dark",
  language: "en"
};

// ✅ Reading works fine
console.log(settings.theme); // "dark"

// ❌ Error: Cannot assign to 'theme' because it is a read-only property
settings.theme = "light";

// ❌ Error: Index signature in type 'Config' only permits reading
settings.newSetting = "value";

The readonly modifier tells TypeScript: "You can access any string-keyed property, but you cannot add, change, or delete them."

Common Use Cases

This pattern is perfect for configuration objects, lookup tables, or data that should remain immutable after initialization:

type ErrorMessages = {
  readonly [code: number]: string;
};

const errors: ErrorMessages = {
  404: "Not Found",
  500: "Server Error"
};

// Safe to read
const message = errors[404];

// Prevented at compile time
// errors[403] = "Forbidden"; // Error!

Key Takeaway: Combining readonly with index signatures prevents all modifications to dynamically keyed properties, creating compile-time immutability for flexible object structures.