Sub topic 3
Readonly Fields in Classes
Assume basic TypeScript syntax, interfaces, type aliases, union types, and JavaScript objects and arrays.
Readonly fields in classes
A readonly class field can be assigned in its declaration or in the constructor. After construction, other methods cannot assign to it.
class Account {
readonly id: string;
balance = 0;
constructor(id: string) {
this.id = id;
}
rename(newId: string): void {
// this.id = newId; // Error: Cannot assign to 'id'
}
}
const account = new Account("A-100");
account.balance = 50;
// account.id = "A-200"; // Errorreadonly is checked by the compiler. It does not freeze the object at runtime.
Changing modifiers in bulk
Utility types transform every property in an object type:
Partial<T>makes every property optional.Required<T>makes every property required.Readonly<T>makes every property readonly.
Mapped-type modifiers remove modifiers:
-?removes optionality.-readonlyremoves readonly.
interface Profile {
readonly id: number;
nickname?: string;
}
type Draft = Partial<Profile>;
type Complete = Required<Profile>;
type Locked = Readonly<Profile>;
type Editable<T> = {
-readonly [K in keyof T]: T[K];
};
type Filled<T> = {
[K in keyof T]-?: T[K];
};
const draft: Draft = {};
const full: Filled<Profile> = { id: 1, nickname: "Ada" };
const editable: Editable<Profile> = { id: 1 };
editable.id = 2;These transformations affect types only. They do not copy or freeze values.
`const` assertions for literal, readonly data
A const assertion uses as const to preserve literal types and mark object properties and arrays as readonly.
const directions = ["up", "down"] as const;
type Direction = (typeof directions)[number]; // "up" | "down"
const origin = { x: 0, y: 0 } as const;
// origin.x = 1; // ErrorDirection is a union of the two allowed strings, rather than string.
Going deeper: recursive `DeepReadonly`
When nested data must also be protected, define a recursive type.
type DeepReadonly<T> =
T extends (...args: any[]) => any ? T :
T extends readonly unknown[] ? ReadonlyArray<DeepReadonly<T[number]>> :
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: ["a"] }
};
// settings.ui.theme = "light"; // Error
// settings.ui.tags.push("b"); // ErrorThis still provides compile-time protection, not runtime freezing.
Exercise
Can a readonly class field be assigned inside its constructor, and does readonly freeze nested arrays?
Show answer
Yes, the constructor may assign the field. No, readonly is shallow and does not freeze nested arrays.