Readonly Properties Basics
You'll learn how to prevent accidental property changes using the readonly modifier in TypeScript.
What Does readonly Do?
Think of readonly like a padlock on a specific property: once you set it during object creation, no one (including you) can change it later. It's TypeScript's way of saying "this value should never be reassigned after initialization."
The Core Idea
In JavaScript, all object properties can be reassigned anytime. But sometimes you want to enforce that certain values stay constant after an object is created — like a user's ID, a creation timestamp, or configuration values that shouldn't change.
The readonly modifier makes TypeScript throw a compile-time error if you try to reassign that property:
type User = {
readonly id: number;
name: string;
};
const user: User = {
id: 101,
name: "Alice"
};
user.name = "Alicia"; // ✅ Fine — name is mutable
user.id = 202; // ❌ Error: Cannot assign to 'id' because it is a read-only property
readonly vs Optional
These modifiers work together but serve different purposes:
type Config = {
readonly apiKey: string;
readonly timeout?: number; // Can combine readonly with ?
};
const config: Config = { apiKey: "abc123" };
config.apiKey = "xyz"; // ❌ Error: read-only
config.timeout = 5000; // ❌ Error: read-only (even though it's optional)
Once initialized (or left undefined), readonly properties are locked.
Key Takeaway: Use readonly to protect properties from reassignment after object creation, preventing accidental mutations and documenting immutable intent in your types.