Deep Readonly Limitations
What you'll learn: You'll discover why TypeScript's readonly modifier only protects the immediate properties of an object, not nested ones.
The Shallow Nature of Readonly
When you mark a property as readonly, TypeScript prevents you from reassigning that specific property. However, if that property is an object or array, TypeScript doesn't automatically make its properties readonly too. The protection is only one level deep—it's "shallow," not "deep."
Think of it like a security checkpoint at a building entrance. The guard checks your ID before you enter (the readonly check), but once you're inside, you can freely rearrange the furniture in the rooms (mutate nested objects). The guard doesn't follow you around enforcing rules in every room.
How This Manifests in Code
type User = {
readonly name: string;
readonly address: {
street: string;
city: string;
};
};
const user: User = {
name: "Alice",
address: {
street: "123 Main St",
city: "Boston"
}
};
user.name = "Bob"; // ❌ Error: Cannot assign to 'name' because it is a read-only property
user.address = { street: "456 Oak Ave", city: "NYC" }; // ❌ Error: readonly prevents reassignment
user.address.street = "789 Elm Dr"; // ✅ Allowed! The nested properties aren't protected
user.address.city = "Seattle"; // ✅ Also allowed!
The address property itself cannot be replaced, but you can freely modify street and city because they aren't marked readonly.
Key Takeaway: TypeScript's readonly modifier is shallow—it only prevents reassignment of the immediate property, not mutations of nested objects within it. To protect nested properties, you must apply readonly at every level.