Course contentsShow
← TypeScript
Lesson 342 of 1,7968. Interfaces vs Type AliasesFree lesson

Readonly Properties in Interfaces

Use readonly to prevent property reassignment after initialization.

Readonly Properties in Interfaces

You'll learn how to lock down interface properties so they can only be set once and never reassigned afterward.

The Core Idea

Just like you can mark properties as readonly in object type literals, you can use the same readonly modifier in interfaces. This tells TypeScript: "This property can be set during initialization, but it should never be reassigned later." It's a compile-time safety feature—nothing prevents runtime modification, but TypeScript will catch accidental reassignments during development.

Think of it like writing in permanent marker vs. pencil. A readonly property is written in permanent marker when the object is created—you can look at it forever, but you can't erase and rewrite it.

Using readonly in Interfaces

interface User {
  readonly id: string;
  name: string;
}

const user: User = {
  id: "abc123",
  name: "Alice"
};

user.name = "Alicia"; // ✅ Fine, name is not readonly
user.id = "xyz789";   // ❌ Error: Cannot assign to 'id' because it is a read-only property

The id can be set when you create the user object, but any attempt to change it later triggers a type error.

Why This Matters

Readonly properties help you model immutable data at the type level. IDs, timestamps, configuration values—anything that shouldn't change after creation—can be marked readonly to prevent accidental bugs. TypeScript will warn you before runtime errors happen.

Key Takeaway: Use readonly in interfaces to prevent property reassignment after initialization, catching accidental mutations at compile time.