Sub topic 2
Locking Properties with `readonly`
Assume basic TypeScript object types, interfaces, union types, and JavaScript arrays.
Locking properties with `readonly`
readonly marks a property as assignable only when an object is created. Later assignments through that property produce a compiler error.
interface Point {
readonly x: number;
readonly y: number;
}
const origin: Point = { x: 0, y: 0 };
// origin.x = 5; // Error: Cannot assign to 'x' because it is read-only.
const moved: Point = { ...origin, x: 5 };
console.log(moved);To change a readonly value, create a new object instead of modifying the existing one.
Readonly is shallow and exists only at compile time
Readonly protection applies to the property itself, not automatically to nested data.
interface Config {
readonly tags: string[];
}
const config: Config = { tags: ["typescript"] };
config.tags.push("javascript"); // Allowed: the array is still mutable.
// config.tags = []; // Error: the tags property is readonly.The compiler removes type annotations when it emits JavaScript. Therefore, readonly does not prevent changes from JavaScript, casts, or other aliases at runtime.
Why `readonly` does not affect assignability
TypeScript allows a readonly property to be assigned to a type with a mutable property. This supports passing readonly data to functions that only read it, but aliasing can bypass the protection.
interface Frozen {
readonly count: number;
}
interface Mutable {
count: number;
}
const frozen: Frozen = { count: 1 };
const mutable: Mutable = frozen; // Allowed
mutable.count = 2;
console.log(frozen.count); // 2The two variables refer to the same object. readonly restricted the frozen.count expression, not every possible reference to that object.
Readonly arrays and tuples
Use readonly T[] when a function should read an array without changing it. Mutable arrays can be passed to such functions.
function total(values: readonly number[]): number {
return values.reduce((sum, value) => sum + value, 0);
}
const numbers = [2, 4, 6];
console.log(total(numbers));A readonly tuple also prevents changing its elements or length. as const infers readonly tuples and readonly object properties.
const direction = ["up", "down"] as const;
// direction[0] = "left"; // Error
type Direction = (typeof direction)[number]; // "up" | "down"Exercise
What can readonly tags: string[] prevent, and what can it still allow?
Show answer
It prevents assigning a new array to tags, but it still allows mutations such as config.tags.push("new").