Sub topic 9
Readonly fields in classes
This chapter assumes you can write TypeScript classes with constructors and methods, and that you know readonly on interface properties and the shallow nature of readonly from earlier chapters. Here we apply readonly to class fields, which have a few rules and edge cases of their own.
What readonly does on a class field
A readonly field can be written during initialization and never afterward. The compiler reports an error for any later assignment, whether it comes from a method, from outside the class, or from a subclass.
class Account {
readonly id: string;
readonly createdAt: Date = new Date();
balance = 0;
constructor(id: string) {
this.id = id; // allowed: the constructor may assign readonly fields
}
rename(newId: string): void {
// this.id = newId; // Error: Cannot assign to 'id' because it is a read-only property.
}
}
const acct = new Account("A-1");
// acct.id = "A-2"; // Error: Cannot assign to 'id' because it is a read-only property.
acct.balance = 10; // fine: balance is not readonlyBoth id and createdAt are readonly, but they are initialized in different places. That difference is the first rule to learn.
Where assignment is allowed
A readonly field can be assigned in exactly two places inside its own class: the field declaration's initializer and the constructor. The compiler checks this by looking at the code that contains the assignment, so a few cases that look similar are rejected.
| Location of the assignment | Allowed? |
|---|---|
| Field initializer (`readonly x = 1`) | Yes |
| Constructor body of the declaring class, through `this` | Yes |
| Method or accessor of the same class | No |
| Function or arrow function nested inside the constructor | No |
| Constructor of a subclass | No |
| Code outside the class | No |
Inside the constructor you are not limited to one assignment. You can compute the value, assign it conditionally, or overwrite it before the constructor returns.
class Token {
readonly value: string;
constructor(raw: string) {
this.value = raw.trim();
if (this.value === "") {
this.value = "anonymous"; // a second assignment is still inside the constructor
}
}
}
console.log(new Token(" abc ").value); // abc
console.log(new Token(" ").value); // anonymousNested functions and subclasses
An arrow function declared inside the constructor does not count as the constructor, even though it can see this. A subclass constructor also fails, because the field belongs to the base class.
class Base {
readonly id: string;
constructor(id: string) {
this.id = id;
const later = () => {
// this.id = "x"; // Error: Cannot assign to 'id' because it is a read-only property.
};
later();
}
}
class Child extends Base {
constructor(id: string) {
super(id);
// this.id = id + "!"; // Error: the base class owns this field
}
}If a subclass needs to influence the value, pass it through the base constructor's parameters.
Parameter properties
A constructor parameter with a modifier (readonly, private, public, or protected) declares a field and assigns it in one step. This is a parameter property.
class Order {
constructor(
readonly id: string,
private readonly lines: readonly string[],
) {}
get count(): number {
return this.lines.length;
}
}
const order = new Order("O-1", ["pen", "ink"]);
console.log(order.id, order.count); // O-1 2readonly can be combined with an access modifier, and the order is always the access modifier first (private readonly).
Readonly changes the inferred type of initializers
For a mutable field, TypeScript widens a literal initializer to its general type. For a readonly field, the value can never change, so TypeScript keeps the literal type.
class Shape {
readonly kind = "shape"; // type is "shape"
name = "shape"; // type is string
}
const sh = new Shape();
const k: "shape" = sh.kind; // OK
// const n: "shape" = sh.name; // Error: Type 'string' is not assignable to type '"shape"'.This is useful for discriminated unions, where each class carries a fixed tag. Declaring readonly kind = "circle" lets the compiler narrow on kind without a separate annotation.
class Circle {
readonly kind = "circle";
constructor(readonly radius: number) {}
}
class Square {
readonly kind = "square";
constructor(readonly side: number) {}
}
function area(s: Circle | Square): number {
return s.kind === "circle" ? Math.PI * s.radius ** 2 : s.side ** 2;
}
console.log(area(new Square(3))); // 9A static readonly field works the same way, for example static readonly MAX = 10, and its type is the literal 10.
Readonly is shallow here too
As with interfaces, readonly on a field protects the reference, not the object behind it. A readonly items: string[] field cannot be reassigned, but you can still push to the array.
class Cart {
readonly items: string[] = [];
add(item: string): void {
this.items.push(item); // allowed: only the items property is readonly
}
}
const cart = new Cart();
cart.add("book");
// cart.items = []; // Error: Cannot assign to 'items' because it is a read-only property.
console.log(cart.items); // [ 'book' ]To keep outside code from mutating the contents, combine three things: keep the field private, keep it readonly so the class itself never replaces it, and expose it through a getter typed as a readonly array.
class Playlist {
private readonly tracks: string[] = [];
add(track: string): void {
this.tracks.push(track);
}
get all(): readonly string[] {
return this.tracks;
}
}
const pl = new Playlist();
pl.add("Intro");
console.log(pl.all.length); // 1
// pl.all.push("Hack"); // Error: Property 'push' does not exist on type 'readonly string[]'.The getter returns the real array, only with a narrower type. If callers might bypass types (plain JavaScript, a cast), return a copy with [...this.tracks] instead. The cost is an allocation on every read.
The same idea applies to ReadonlyMap<K, V> and ReadonlySet<T>, which remove set, delete, add, and clear from the type.
Getters as read-only properties
An accessor with a get and no matching set is also read-only. Assigning to it is the same compile-time error as for a readonly field.
class Temperature {
constructor(private celsius: number) {}
get fahrenheit(): number {
return (this.celsius * 9) / 5 + 32;
}
}
const t = new Temperature(20);
console.log(t.fahrenheit); // 68
// t.fahrenheit = 100; // Error: Cannot assign to 'fahrenheit' because it is a read-only property.The two forms differ in what they promise. A readonly field stores a value that is fixed after construction. A getter computes a value on each access and may return something different each time, because celsius here is a mutable field. Choose a getter for derived values and readonly for stored identity-like values such as ids and timestamps.
What readonly does not guarantee
readonly is erased when TypeScript compiles to JavaScript. The emitted class has plain, writable properties, so any code that gets past the type checker can change them. Because readonly does not affect assignability, a readonly field can be reached through a mutable alias type without any any at all.
class Ticket {
constructor(readonly id: string) {}
}
const ticket = new Ticket("T-1");
const alias: { id: string } = ticket; // allowed: readonly does not affect assignability
alias.id = "T-2";
console.log(ticket.id); // T-2The lesson is the same as in the interface chapter: the compiler checks direct assignments to the readonly name, and it does not track the object through other types.
You have three runtime options, each with a cost:
Object.freeze(this)at the end of the constructor stops writes to existing properties. It is shallow, and in strict mode a write throws aTypeError. Do not call it in a base class constructor if subclasses assign their own fields afterward, because those assignments would fail.- Private
#fields with only a getter make the value unreachable from outside the class at runtime. Nothing outside can write it, but you give up structural access such as spreading the object or logging its internals. - Closures or getter-only access over private state give the same effect with more code.
For most application code, the compile-time check is enough. It catches accidental writes inside your own codebase, which is where most of the bugs are.
Common mistakes
- Assigning in a method. A
setNamemethod on a class withreadonly namefails. Either removereadonly, or return a new instance with the changed value. - Expecting deep protection. A
readonlyfield holding an array or object remains mutable inside. Add a readonly type such asreadonly string[]orReadonly<T>to the field's own type. - Assigning in a callback inside the constructor. Compute the value first, then assign it directly in the constructor body.
- Forgetting a subclass cannot assign it. Route the value through the base constructor.
- Relying on readonly at runtime. It disappears at compile time.
A pattern that follows from the first mistake is the "wither" method, which keeps the class immutable by returning a copy.
class Money {
constructor(
readonly amount: number,
readonly currency: string,
) {}
withAmount(amount: number): Money {
return new Money(amount, this.currency);
}
}
const price = new Money(5, "EUR");
const higher = price.withAmount(8);
console.log(price.amount, higher.amount); // 5 8Exercise
This class fails to compile in two places. Identify both errors and say how to fix each one without removing readonly from id.
class User {
readonly id: string;
readonly roles: string[] = [];
constructor(id: string) {
setTimeout(() => {
this.id = id;
}, 0);
}
promote(): void {
this.roles = ["admin"];
}
}
Show answer
First, this.id = id sits inside an arrow function nested in the constructor, so the compiler does not treat it as constructor code. Assign this.id = id directly in the constructor body. Second, this.roles = ["admin"] in promote assigns a readonly field outside the constructor. Fix it by changing the contents instead of the reference, for example this.roles.push("admin"). Alternatively, make the field private readonly roles: string[] and let promote push to it. Note that push compiles only because readonly is shallow, and this is not protected from outside callers unless the field is private or typed as readonly string[].
Exercise
Given the class below, what does the program print, and does the compiler accept the line that assigns through alias?
class Ticket {
constructor(readonly id: string) {}
}
const ticket = new Ticket("T-1");
const alias: { id: string } = ticket;
alias.id = "T-2";
console.log(ticket.id);
Show answer
It prints T-2, and the compiler accepts the code. A readonly property does not affect assignability, so a Ticket can be assigned to the mutable type { id: string }. The write through alias changes the same object, and readonly is erased at runtime, so nothing stops it.