Sub topic 6
Readonly is shallow and exists only at compile time
This chapter assumes you can write interfaces and type aliases, you know the readonly modifier on a property, and you are comfortable with JavaScript objects and arrays. Earlier chapters showed that readonly blocks reassignment. This chapter covers two limits on that protection.
readonlyapplies to one level of an object: the property itself, not the value it points to.readonlyis erased when TypeScript compiles to JavaScript, so nothing enforces it at runtime.
Both limits explain why a readonly property sometimes changes anyway. Knowing them lets you decide when the modifier is enough and when you need more.
What readonly actually guards
A readonly modifier makes the compiler reject assignments to that property through that type. It checks the assignment expression obj.prop = value. It does not look inside value, and it does not change what value is.
interface Config {
readonly name: string;
readonly tags: string[];
readonly limits: { max: number };
}
const c: Config = { name: "api", tags: ["a"], limits: { max: 10 } };
// c.name = "web"; // Error: Cannot assign to 'name' because it is a read-only property.
// c.tags = []; // Error: Cannot assign to 'tags' because it is a read-only property.
c.tags.push("b"); // allowed
c.limits.max = 99; // allowedThe assignments to c.name and c.tags are rejected. The last two lines are accepted because they do not assign to a readonly property. c.tags.push("b") calls a method on the array, and c.limits.max = 99 assigns to max, which is a different property that is not marked readonly.
Shallow protection
"Shallow" means the modifier covers only the property it is attached to. The diagram shows where the lock sits for Config.
For a primitive such as string, a locked property means a locked value, because primitives cannot be modified in place. For arrays and objects, the property holds a reference. The lock stops you from pointing the property at a different array or object. The existing array or object stays fully mutable unless its own type says otherwise.
Fixing one level at a time
You can extend the protection by marking the inner types as readonly too.
interface SafeConfig {
readonly name: string;
readonly tags: readonly string[];
readonly limits: { readonly max: number };
}
const s: SafeConfig = { name: "api", tags: ["a"], limits: { max: 10 } };
// s.tags.push("b"); // Error: Property 'push' does not exist on type 'readonly string[]'.
// s.limits.max = 99; // Error: Cannot assign to 'max' because it is a read-only property.The readonly string[] type removes the mutating methods (push, pop, splice, sort and the others) and makes index writes an error. The { readonly max: number } type locks the nested property. You have to do this at every level, which gets tedious for deep structures. The last chapter of this tutorial builds a recursive DeepReadonly type to automate it.
The Readonly utility type is shallow too
The built-in Readonly<T> is a mapped type that adds readonly to each top-level property. It does not recurse.
interface Settings {
ui: { theme: string };
}
const frozenSettings: Readonly<Settings> = { ui: { theme: "dark" } };
// frozenSettings.ui = { theme: "light" }; // Error: read-only
frozenSettings.ui.theme = "light"; // allowed: ui.theme is not readonlyA common mistake is to wrap a type in Readonly<...> and assume the whole tree is locked. Only the first level is.
Copies share nested values
A spread copy is also shallow, so it produces a new top-level object whose nested values are the same references.
const original: SafeConfig = { name: "api", tags: ["a"], limits: { max: 10 } };
const copy = { ...original, name: "web" };
console.log(copy.tags === original.tags); // true: same arrayHere the types protect you, because tags is readonly string[]. If the type were a plain string[], a push through copy.tags would also change original.tags. Sharing is cheap and safe only when nothing mutates the shared parts, which is the point of making them readonly.
Readonly exists only at compile time
TypeScript's type annotations, including readonly, are removed when the code is compiled to JavaScript. JavaScript objects have no concept of a TypeScript readonly property. Compile this:
interface Point {
readonly x: number;
readonly y: number;
}
const p: Point = { x: 1, y: 2 };
console.log(p.x);The emitted JavaScript is, apart from formatting, this:
const p = { x: 1, y: 2 };
console.log(p.x);The interface is gone, and so is the modifier. The emitted object is an ordinary mutable object. Anything that runs without going through the type checker can change it.
Ways the lock is bypassed
Several ordinary situations let a write through even though the declared type says readonly.
interface Point {
readonly x: number;
readonly y: number;
}
const p: Point = { x: 1, y: 2 };
(p as { x: number }).x = 99; // type assertion to a mutable type
console.log(p.x); // 99
(p as any).y = 42; // any turns the checker off
console.log(p.y); // 42The same thing happens in these cases:
- Plain JavaScript code, or a JavaScript dependency, calls your function and modifies the object.
- Data comes from
JSON.parseor a network response and is typed asPointwithout validation. The type is a claim and nothing checks it. - Another reference to the same object has a mutable type. The next chapter covers this aliasing case.
A related consequence is that you cannot test for readonly in code. There is no if (isReadonly(obj.x)), because at runtime the information does not exist.
Getting real enforcement: Object.freeze
If you need runtime enforcement, use JavaScript's own mechanism, Object.freeze. It marks the properties of an object as non-writable. TypeScript's typing of Object.freeze returns a Readonly type, so the compiler and the runtime then agree.
const frozen = Object.freeze({ x: 1, nested: { y: 2 } });
// frozen.x = 5; // compile error: x is read-only
frozen.nested.y = 3; // allowed by the compiler and by the runtime
console.log(frozen.nested.y); // 3
try {
(frozen as { x: number }).x = 5; // bypass the compiler with a cast
} catch (e) {
console.log(e instanceof TypeError); // true in strict mode
}
console.log(frozen.x); // 1Three details matter here.
- In strict mode code, assigning to a frozen property throws a
TypeError. In sloppy-mode scripts the assignment fails silently. Settingstrict: trueintsconfig.jsonmakes TypeScript emit"use strict", and ES modules are always strict. Object.freezeis also shallow.frozen.nestedis not frozen, sofrozen.nested.y = 3succeeds at runtime as well as at compile time. To freeze a whole tree you must walk it and freeze each object.- Freezing has a runtime cost and cannot be undone. Use it at boundaries where you need a guarantee, such as shared constants, and not on every object.
Choosing between the two
| Approach | Checked when | Depth | Typical use |
|---|---|---|---|
| `readonly` property | Compile time only | One level per modifier | Documenting and enforcing intent inside your own typed code |
| `readonly T[]` | Compile time only | The array itself, not its elements | Function parameters that must not modify input |
| `Object.freeze` | Runtime, plus `Readonly` typing | One level | Shared constants and data that untrusted code might touch |
| Recursive freeze plus `DeepReadonly` | Both | Whole tree | Configuration or state that must never change |
Common errors and how to read them
- "Cannot assign to 'x' because it is a read-only property." This is TS2540. Create a new object with a spread (
{ ...p, x: 5 }) instead of mutating. - "Property 'push' does not exist on type 'readonly string[]'." The array type is readonly, so the method is missing from the type. Copy first (
[...xs, item]) or accept a mutable array if mutation is intended. - No error where you expected one. Check whether the readonly modifier is only on the outer property. If the inner value is a plain array or object type, mutation of its contents is legal.
- A value changed even though every type was readonly. Look for
ascasts,any, an alias with a mutable type, or an untyped JavaScript caller.
Putting it together
Consider a function that receives configuration and promises not to change it.
interface ServerOptions {
readonly host: string;
readonly ports: readonly number[];
readonly tls: { readonly cert: string; readonly key: string };
}
function describe(options: ServerOptions): string {
// options.ports.push(80); // Error: 'push' does not exist on type 'readonly number[]'
// options.tls.cert = "x"; // Error: read-only
return `${options.host}:${options.ports.join(",")}`;
}
const opts = Object.freeze({
host: "localhost",
ports: Object.freeze([8080, 8443]),
tls: Object.freeze({ cert: "a.pem", key: "a.key" }),
});
console.log(describe(opts)); // localhost:8080,8443The type annotations make the promise visible to the compiler at each level. The Object.freeze calls make it true at runtime at each level. The two layers are independent. You can have either one without the other, and for most application code the types alone are enough.
Exercise
Given interface Box { readonly items: string[]; readonly meta: { id: number } } and const b: Box = { items: [], meta: { id: 1 } }, which of these lines compile without error: b.items = [], b.items.push("x"), b.meta.id = 2, b.meta = { id: 3 }? Then change the Box interface so that none of them compile.
Show answer
Only b.items.push("x") and b.meta.id = 2 compile. b.items = [] and b.meta = { id: 3 } assign to readonly properties. The readonly modifiers on items and meta do not cover the array's contents or the property id. To block all four, write interface Box { readonly items: readonly string[]; readonly meta: { readonly id: number } }.
Exercise
A teammate says "I typed the parsed response as Readonly<User>, so nobody can modify it, even at runtime." Give two reasons this is wrong, and name one thing you could do to enforce it at runtime.
Show answer
First, readonly is erased when the code is compiled, so the emitted JavaScript object is an ordinary mutable object and a cast, any, or JavaScript caller can change it. Second, Readonly<User> is shallow, so nested objects and arrays inside the user remain mutable even in the type system. To enforce it at runtime, call Object.freeze on the object (and on nested objects and arrays, since freezing is also shallow). A strict-mode write to a frozen property then throws a TypeError.