Skip to main content

readonly

What readonly does

The readonly modifier marks a property as assign-once: you can set it when the object is created, but any later reassignment is a compile error.

type User = {
readonly id: string;
name: string;
};

const u: User = { id: "abc", name: "Ajay" };
u.name = "Ravi"; // Valid: normal property
u.id = "xyz"; // Error: Cannot assign to 'id' because it is a read-only property

It's compile-time only, and shallow

readonly is erased at runtime — nothing stops mutation in the emitted JavaScript; it's purely a check for you while coding. It's also shallow: a readonly array or object can still have its contents changed.

const nums: readonly number[] = [1, 2, 3];
nums.push(4); // Error: push doesn't exist on readonly arrays
nums[0] = 9; // Error: index assignment blocked

type Box = { readonly items: string[] };
const b: Box = { items: ["a"] };
b.items = []; // Error: can't reassign the property
b.items.push("x"); // Valid: but the array itself is still mutable

readonly protects the binding, not the value. It documents intent and catches accidental reassignment, but it's a type-level guardrail, not a runtime freeze (that's Object.freeze).