Sub topic 9
readonly properties
This chapter assumes you know TypeScript field declarations, constructors, and the public and private modifiers from the earlier chapters. It covers what readonly guarantees, where assignment is allowed, and where the guarantee stops.
What readonly does
A readonly property can be assigned only in two places: its declaration (as an initializer) and the constructor of the class that declares it. Everywhere else, including the class's own methods, assignment is a compile-time error.
class User {
readonly id: string;
readonly createdAt: Date = new Date();
constructor(id: string, private name: string) {
this.id = id; // allowed: constructor of the declaring class
}
rename(next: string): void {
this.name = next; // allowed: name is not readonly
// this.id = "x"; // Error: Cannot assign to 'id' because it is a read-only property.
}
}
const user = new User("u-1", "Ada");
console.log(user.id); // u-1
// user.id = "u-2"; // Error: Cannot assign to 'id' because it is a read-only property.Reading is unrestricted. readonly only removes the ability to write.
Modifier order and combinations
When you combine an accessibility modifier with readonly, the accessibility modifier comes first: private readonly, protected readonly, public readonly. Writing readonly private is a syntax error.
Parameter properties accept readonly too, so a constructor can declare and assign a field in one step:
class Config {
constructor(
public readonly host: string,
public readonly port: number,
private readonly secret: string
) {}
url(): string {
return `https://${this.host}:${this.port}`;
}
}
console.log(new Config("example.com", 443, "s3cret").url()); // https://example.com:443Use private readonly for dependencies and internal values that are set once. It states two facts: outside code cannot see the field, and nothing inside the class changes it.
Conditional initialization in the constructor
The constructor may assign a readonly property more than once, and inside branches. This is useful when the value depends on arguments.
class Connection {
readonly protocol: "http" | "https";
constructor(secure: boolean) {
if (secure) {
this.protocol = "https";
} else {
this.protocol = "http";
}
}
}
console.log(new Connection(true).protocol); // httpsUnder strictPropertyInitialization, a readonly property with no initializer must be definitely assigned on every path through the constructor. Assigning it in a helper method does not count, so the compiler reports an error.
readonly infers narrower types
A mutable field initialized with a literal gets the widened type. A readonly field keeps the literal type, because the value can never change.
class Circle {
readonly kind = "circle"; // type is "circle"
label = "circle"; // type is string
}
const circle = new Circle();
const k: "circle" = circle.kind; // OK
// const l: "circle" = circle.label; // Error: Type 'string' is not assignable to type '"circle"'.
console.log(k); // circleThis makes readonly kind = "..." a convenient discriminant for tagged unions built from classes.
readonly is shallow
readonly stops reassignment of the property. It does not stop mutation of the object the property refers to.
class Playlist {
readonly tracks: string[] = [];
readonly owner: { name: string };
constructor(name: string) {
this.owner = { name };
}
}
const list = new Playlist("Ada");
list.tracks.push("Song A"); // allowed: the array itself is mutable
list.owner.name = "Grace"; // allowed: the nested object is mutable
// list.tracks = []; // Error: read-only property
console.log(list.tracks, list.owner.name); // [ 'Song A' ] GraceTo block mutation of the contents, make the type itself read-only:
class SafePlaylist {
readonly tracks: readonly string[];
constructor(tracks: string[]) {
this.tracks = [...tracks]; // copy, so the caller's array cannot change ours
}
}
const safe = new SafePlaylist(["A", "B"]);
console.log(safe.tracks.length); // 2
// safe.tracks.push("C"); // Error: Property 'push' does not exist on type 'readonly string[]'.Copying in the constructor matters. Without the copy, the caller still holds a mutable reference to the same array, and the type-level protection does not help them.
readonly is not enforced at runtime
readonly is erased when TypeScript compiles to JavaScript. It also does not affect type compatibility. A class with a readonly property is assignable to a type with the same property as mutable, so the compiler lets you write through the second type.
class Settings {
constructor(public readonly port: number) {}
}
const settings = new Settings(80);
const mutable: { port: number } = settings; // allowed
mutable.port = 8080;
console.log(settings.port); // 8080Plain JavaScript callers and any casts bypass it as well. If you need runtime enforcement, you have these options:
| Technique | Enforced at | Notes |
|---|---|---|
| `readonly` | Compile time | No runtime cost, no runtime protection |
| `Object.freeze(this)` in the constructor | Runtime | Shallow. Writes fail silently, or throw in strict mode |
| `#field` with a getter | Runtime | The value cannot be reached from outside the class |
| Getter with no setter | Compile time and runtime | Assignment throws in strict mode (class bodies are always strict) |
readonly versus a getter-only accessor
Both give callers a value they cannot assign. A getter runs code on every read, so it suits computed values. A readonly field stores a value and has no per-read cost. A getter can also hide a private field, which a readonly field cannot.
Inheritance
Only the declaring class's constructor may assign a readonly property. A subclass constructor cannot reassign an inherited one.
class Base {
constructor(readonly id: string) {}
}
class Derived extends Base {
constructor() {
super("d-1");
// this.id = "d-2"; // Error: Cannot assign to 'id' because it is a read-only property.
}
}
console.log(new Derived().id); // d-1If a subclass needs to set the value, pass it up through super(...).
Exercise
A class declares readonly items: readonly string[] and its constructor does this.items = items; where items is a string[] parameter. Callers later push to their original array. Does the class's items change, and what is the fix?
Show answer
Yes. Both variables refer to the same array, and readonly only blocks reassigning the property and calling mutating methods through the read-only type. The caller's mutable reference still works. The fix is to copy in the constructor: this.items = [...items];.
Exercise
Why does class A { readonly n = 5; m = 5; } give n the type 5 and m the type number?
Show answer
A mutable property can later hold any number, so TypeScript widens the literal to number. A readonly property can never be reassigned, so its type stays the literal 5.