Sub topic 5
Locking Properties with `readonly`
Assume you know basic TypeScript annotations, interfaces, type aliases, union types, and JavaScript objects and arrays. This chapter focuses on the readonly property modifier and the guarantees it gives during type checking.
Marking a property as read-only
readonly is a TypeScript modifier that prevents assignment to a property after the object has been created.
interface Point {
readonly x: number;
readonly y: number;
}
const start: Point = { x: 0, y: 0 };
console.log(start.x); // 0
// start.x = 10;
// Error: Cannot assign to 'x' because it is a read-only property.The object still contains ordinary JavaScript properties at runtime. TypeScript checks the attempted assignment while compiling your program, but it does not add a runtime lock to the object.
A read-only property can be assigned when the object is initialized:
const origin: Point = { x: 0, y: 0 };After initialization, create a new object when you need a changed value:
const moved: Point = {
...origin,
x: 5
};
console.log(origin.x); // 0
console.log(moved.x); // 5The spread syntax copies the existing properties into a new object. The new object has the same Point type, but the original value remains unchanged.
Readonly is shallow
readonly applies to the property itself, not automatically to the value stored inside it. This matters when the property contains an object or an array.
interface Config {
readonly tags: string[];
}
const config: Config = {
tags: ["typescript"]
};
config.tags.push("objects"); // Allowed
// config.tags = []; // ErrorThe tags property cannot be replaced, but the array referenced by tags is still mutable. Calling push changes that array without assigning a new value to config.tags.
To prevent changes to the array through this type, use a read-only array:
interface SafeConfig {
readonly tags: readonly string[];
}
const safeConfig: SafeConfig = {
tags: ["typescript"]
};
// safeConfig.tags.push("objects");
// Error: Property 'push' does not exist on type 'readonly string[]'.A readonly array can be read and iterated, but methods that change its length or elements are unavailable.
Readonly does not change assignability
A read-only view can be assigned to a mutable type:
interface MutablePoint {
x: number;
}
interface FrozenPoint {
readonly x: number;
}
const frozen: FrozenPoint = { x: 1 };
const mutable: MutablePoint = frozen;
mutable.x = 2;
console.log(frozen.x); // 2Both variables refer to the same object. The FrozenPoint type prevents assignment through frozen, but MutablePoint permits assignment through mutable.
This is why readonly is not a complete immutability guarantee. It is useful for expressing intent and preventing accidental writes through particular references, but aliases with mutable types can still change the object.
For function parameters, prefer a read-only type when the function only needs to inspect data:
function sum(values: readonly number[]): number {
return values.reduce((total, value) => total + value, 0);
}
const numbers = [1, 2, 3];
console.log(sum(numbers)); // 6A mutable number[] can be passed to a parameter typed as readonly number[]. The function promises not to modify the caller's array, while callers can continue using ordinary arrays.
Exercise
In the following code, which operation is rejected by TypeScript, and what change would make the array itself read-only? interface Basket { readonly items: string[]; } const basket: Basket = { items: ["apple"] }; basket.items.push("orange"); basket.items = [];
Show answer
The assignment basket.items = [] is rejected because the items property is readonly. The push call is allowed because readonly is shallow. Change the declaration to readonly items: readonly string[] to reject both operations.