Sub topic 6
Readonly Is Shallow and Exists Only at Compile Time
This chapter assumes basic TypeScript syntax, interfaces, type aliases, union types, and JavaScript objects and arrays. You should also know that TypeScript checks types before JavaScript runs.
The readonly modifier tells TypeScript that a property should not be reassigned after its object is created:
interface Point {
readonly x: number;
readonly y: number;
}
const point: Point = { x: 10, y: 20 };
// point.x = 15;
// Error: Cannot assign to 'x' because it is a read-only property.The compiler reports an error for point.x = 15. However, readonly does not add a runtime lock to the JavaScript object.
Readonly is shallow
A readonly property protects the property itself. It does not automatically protect the value stored inside that property.
interface Config {
readonly tags: string[];
}
const config: Config = {
tags: ["typescript"],
};
config.tags.push("javascript"); // Allowed
console.log(config.tags); // ["typescript", "javascript"]
// config.tags = []; // ErrorThe tags property cannot be replaced with another array. The array that it refers to can still be changed through methods such as push, pop, and splice.
This distinction matters for nested objects too:
interface User {
readonly profile: {
name: string;
};
}
const user: User = {
profile: { name: "Ada" },
};
user.profile.name = "Grace"; // Allowed
// user.profile = { name: "Grace" }; // ErrorThe reference stored in profile is readonly. The name property inside the referenced object is still mutable.
To protect nested values, each nested level needs a readonly type. A recursive type can apply the modifier throughout an object:
type DeepReadonly<T> =
T extends (...args: any[]) => any
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
interface Settings {
ui: {
theme: string;
tags: string[];
};
}
const settings: DeepReadonly<Settings> = {
ui: {
theme: "dark",
tags: ["compact"],
},
};
// settings.ui.theme = "light"; // Error
// settings.ui.tags.push("large"); // ErrorDeepReadonly recursively visits object properties. It also turns arrays into readonly array-like values, so mutating methods such as push are unavailable.
Readonly exists only at compile time
TypeScript removes type annotations and modifiers when it produces JavaScript. The generated JavaScript does not know that x or tags was declared readonly.
For example, this TypeScript code:
interface Counter {
readonly value: number;
}
const counter: Counter = { value: 1 };
// counter.value = 2; // TypeScript errordoes not automatically create a frozen JavaScript object. Code that bypasses the type checker, uses JavaScript, or receives data from another system can still mutate the object.
Use Object.freeze when you need a runtime-level restriction:
const frozenCounter = Object.freeze({ value: 1 });
// frozenCounter.value = 2; // TypeScript error and a runtime failureObject.freeze is also shallow. It freezes the outer object, but nested objects require their own freezing. A recursive freeze function is needed for deep runtime protection.
Choose the right guarantee
Use readonly when a function should observe data without changing it:
function total(values: readonly number[]): number {
return values.reduce((sum, value) => sum + value, 0);
}
const numbers = [2, 4, 6];
console.log(total(numbers)); // 12The parameter accepts both mutable and readonly arrays, but the function cannot call mutating methods on values. This expresses a useful contract: the function reads the collection and does not modify it.
Use Object.freeze or another runtime mechanism when code must be protected after compilation. Use deep readonly types when you want the compiler to check nested access as well. These choices solve different problems and can be combined.
Exercise
In the following code, which operation is rejected by TypeScript, and which operation is allowed? Explain why: interface Box { readonly items: string[] }, followed by box.items = [] and box.items.push("x").
Show answer
Assigning box.items = [] is rejected because the outer items property is readonly. Calling box.items.push("x") is allowed because the array value remains mutable; readonly is shallow.