Typescript Foundations / Class & Object Oriented Typescript

Readonly properties

The readonly modifier ensures that a property can only be assigned once — either during:

  • Initialization, or

  • Inside the constructor

After that, it cannot be changed.


🌟 Basic Example

class Book {
  readonly title: string;

  constructor(title: string) {
    this.title = title;
  }
}

const myBook = new Book("TypeScript Handbook");
console.log(myBook.title); // ✅ OK

myBook.title = "New Title";  //❌ Error: Cannot assign to 'title' because it is a read-only property

✅ Use Cases

Use Case

Why Use readonly

Unique IDs

Prevent accidental changes

Config values

Ensure immutability

Constant properties in classes

Enforce stability after construction


🧱 Readonly with Arrays

Use ReadonlyArray<T> or readonly modifier on arrays to prevent mutations:

const numbers: ReadonlyArray<number> = [1, 2, 3];

// numbers.push(4);     ❌ Error
// numbers[0] = 100;     ❌ Error

✨ With Constructor Shorthand

You can combine readonly with the constructor’s parameter property syntax:

class Student {
  constructor(
    public name: string,
    readonly id: number
  ) {}
}

const s = new Student("Tisha", 123);
// s.id = 999; ❌ Error

✅ Summary Table

Feature

Description

readonly

Property can be assigned only once

Where to use

Classes, interfaces, type aliases, arrays

Works with

Primitive values, objects, arrays

Common use

IDs, configuration, constants