readonly Modifier
What you'll learn: How to make class properties unchangeable after initialization, adding an extra layer of compile-time safety to your TypeScript classes.
The Core Idea
The readonly modifier works with properties in classes (and interfaces/types) to prevent reassignment after the property is initialized. You can set a readonly property's value during declaration or in the constructor, but after that, TypeScript treats any attempt to change it as a compile-time error.
Think of it like a contract sealed at construction time — once the ink dries (after the constructor runs), no edits allowed.
How It Works with All Access Levels
The readonly modifier is independent of visibility modifiers. You can combine it with public, private, or protected:
class User {
public readonly id: string;
private readonly createdAt: Date;
protected readonly version: number = 1;
constructor(id: string) {
this.id = id;
this.createdAt = new Date();
// Both 'id' and 'createdAt' can be set here
}
updateId(newId: string) {
this.id = newId; // ❌ Error: Cannot assign to 'id' because it is a read-only property
}
}
const user = new User("abc123");
user.id = "xyz"; // ❌ Error: Cannot assign to 'id'
Compile-Time Only Protection
Remember: readonly is a TypeScript feature, not a JavaScript one. At runtime, the compiled JavaScript has no enforcement. It's purely a compile-time safety net to catch accidental mutations in your TypeScript code.
class Config {
readonly apiKey: string;
constructor(key: string) {
this.apiKey = key;
}
}
Key Takeaway: Use readonly to make properties immutable after initialization, working seamlessly with public, private, or protected to prevent accidental reassignments anywhere in your code.