Sub topic 5
Locking properties with readonly
This chapter covers the readonly modifier on object properties: how to declare it, what the compiler rejects, and how to update data you have locked. It assumes you know interfaces, type aliases, and optional properties (?). Later chapters cover its limits (shallow, compile-time only), arrays, classes, and bulk utilities. Here we stay on the basic mechanics and the habits around them.
What readonly does
Put readonly before a property name and the compiler rejects any assignment to that property through that type.
interface Point {
readonly x: number;
readonly y: number;
}
const p: Point = { x: 1, y: 2 };
console.log(p.x); // reading is always fine
// p.x = 5; // Error: Cannot assign to 'x' because it is a read-only property.The error is TS2540. You set the value once, when the object is created, and the type forbids later writes.
The modifier only restricts writing. A readonly property has the same type as before, it is read the same way, and it is still required unless you also add ?.
Where you can declare it
readonly works anywhere a property is declared in a type:
- Interfaces
- Type aliases
- Inline object types, such as a parameter annotation
- Index signatures
- Class fields (covered in its own chapter)
type Coordinates = {
readonly lat: number;
readonly lng: number;
};
function describe(place: { readonly name: string; readonly tags: string[] }): string {
return `${place.name} (${place.tags.length} tags)`;
}
interface Scores {
readonly [player: string]: number;
}
const scores: Scores = { ada: 10, grace: 12 };
console.log(scores.ada);
// scores.ada = 11; // Error: Index signature in type 'Scores' only permits reading.The index-signature form locks every key at once. It is useful for lookup tables you build once and never edit.
The modifier goes before the property name, and ? goes after it. You can combine them:
interface Profile {
readonly id: number;
readonly createdBy?: string; // locked, and may be absent
nickname?: string; // optional but writable
}
const profile: Profile = { id: 7 };
profile.nickname = "ada"; // OK
// profile.id = 8; // Error: read-only
// profile.createdBy = "x"; // Error: read-only, even though it was omittedThe last line surprises people. An omitted readonly optional property cannot be filled in later through this type. If it must be set eventually, either it should not be readonly, or you build a new object.
readonly is not const
const and readonly both stop reassignment, but they guard different things.
| Feature | Applies to | What it blocks |
|---|---|---|
| `const` | A variable binding | Pointing the variable at a different value |
| `readonly` | A property in a type | Assigning to that property through that type |
const a = { count: 0 };
a.count = 1; // OK: const protects the variable, not the object
// a = { count: 2 }; // Error: Cannot assign to 'a' because it is a constant.
interface Counter {
readonly count: number;
}
let c: Counter = { count: 0 };
c = { count: 1 }; // OK: the variable is declared with let
// c.count = 2; // Error: read-only propertyAlso, an object literal with no annotation gets ordinary mutable properties. const a = { count: 0 } has the type { count: number }. Nothing is locked unless a type says so.
Which operations are blocked
The compiler treats every write to the property as an error, not only =.
interface Stats {
readonly hits: number;
readonly label: string;
}
declare const stats: Stats;
// stats.hits = 1; // Error: read-only
// stats.hits += 1; // Error: read-only
// stats.hits++; // Error: read-only
// delete stats.label; // Error: The operand of a 'delete' operator cannot be a read-only property.Compound assignment (+=), increment (++), and delete all count as writes. Reading, passing the value on, and calling methods on it are unaffected.
The check follows the type of the expression you write through, not the object itself. If the compiler sees a mutable type for the same object, the write is allowed. The assignability chapter covers that.
Updating without mutating
If you cannot change a locked object, you create a new one. The usual tool is object spread, which copies the properties and lets later keys override earlier ones.
interface Point {
readonly x: number;
readonly y: number;
}
function moveRight(p: Point, dx: number): Point {
return { ...p, x: p.x + dx };
}
const start: Point = { x: 1, y: 2 };
const next = moveRight(start, 3);
console.log(start); // { x: 1, y: 2 }
console.log(next); // { x: 4, y: 2 }The function returns a Point, so the result is locked again. The type of a spread expression itself has ordinary writable properties, so the return annotation keeps the lock in place. Annotate the result type of functions like this one.
This pattern fits state management, where you compare old and new values by reference, and functions that must not alter their input. Callers can tell from the signature that the argument will not change.
interface Order {
readonly id: string;
readonly status: "open" | "paid" | "shipped";
}
function markPaid(order: Order): Order {
return { ...order, status: "paid" };
}
const open: Order = { id: "A1", status: "open" };
const paid = markPaid(open);
console.log(open.status, paid.status); // open paidNote that status: "paid" type-checks because the return type provides the contextual literal type. Without the annotation, the property would widen to string and fail to match Order.
How the compiler decides
A write to a property goes through a short check. The diagram shows the order.
The first decision depends on the static type at that point in the code. It does not depend on anything stored in the object at runtime.
The lock exists only in the types
TypeScript removes types when it compiles to JavaScript, so readonly leaves no trace in the output. Nothing stops a write that the compiler does not see. For example, Object.assign accepts any target, so this compiles and runs:
interface Point {
readonly x: number;
readonly y: number;
}
const p: Point = { x: 1, y: 2 };
Object.assign(p, { x: 99 }); // no compile error
console.log(p.x); // 99If you need a runtime guarantee, Object.freeze provides one, and its TypeScript signature returns a read-only version of the type. The next chapter explains the limits of both approaches.
Choosing what to lock
Lock properties that should not change after construction. Typical candidates:
- Identifiers such as
id, which other records may reference. - Values derived once, such as a creation timestamp.
- Configuration objects passed to many functions.
- Return values from functions that hand out shared data.
Leave properties writable when the object is a short-lived local buffer or when mutation is the intended way to use it, such as a counter inside a loop. Locking everything makes updates verbose and gives little in return where only one function touches the data.
Common errors
- Assigning in a method or helper.
this.id = xorobj.id = xoutside creation fails. Build a new object instead. - Expecting
readonlyto allow later fill-in of an optional property. Areadonly createdBy?: stringcannot be set after the object exists. - Forgetting the return annotation. Without it, spread results and string literals can widen, and the lock disappears from the result type.
- Assuming runtime protection.
readonlydoes not freeze the object, soObject.assign,any, and untyped code can all write to it. - Putting
readonlyafter the name. The order isreadonly name?: Type. Writingname readonly: Typeis a syntax error.
Summary of the mechanics
The modifier is a compile-time promise attached to a property in a type. It blocks =, +=, ++, and delete through that type. It combines with ?. It does not change the property's type, and it leaves no runtime trace. To change locked data you copy it, usually with spread, and annotate the result so the new object is locked too.
Exercise
Given the interface below, which of the four lines at the bottom produce a compile error, and why? interface Task { readonly id: number; readonly owner?: string; title: string; } const t: Task = { id: 1, title: "Write" }; t.title = "Edit"; // line 1 t.id = 2; // line 2 t.owner = "ada"; // line 3 const u: Task = { ...t, id: 2 }; // line 4
Show answer
Lines 2 and 3 are errors. Line 2 assigns to the readonly property id. Line 3 assigns to the readonly optional property owner, which stays locked even though it was omitted. Line 1 is fine because title is writable. Line 4 is fine because it creates a new object with spread instead of writing to t.
Exercise
Write a function rename(user, name) that takes a User with readonly id: number and readonly name: string, and returns a copy with the new name. Then explain what Object.assign(user, { id: 5 }) does to a User value, and whether the compiler reports it.
Show answer
interface User { readonly id: number; readonly name: string; } function rename(user: User, name: string): User { return { ...user, name }; } Object.assign(user, { id: 5 }) compiles without an error, because Object.assign accepts any target type and the compiler does not check readonly through it. At runtime it changes user.id to 5, since readonly is erased when TypeScript compiles to JavaScript.