← Back to TypeScript Course | Chapter 6: Classes | Lesson 4 of 9

Readonly Members

The readonly modifier prevents a property from being reassigned after it has been initialized. Readonly properties are useful for values that should remain unchanged during the lifetime of an object.

Readonly Properties

A readonly property can be assigned when it is declared or initialized in a constructor, but any assignment attempted after that point is rejected at compile time, even from within the class itself.

Example: Readonly Properties

typescript
class Config {
  readonly version: string = "1.0";
}
const config = new Config();
// config.version = "2.0"; // rejected: readonly
console.log(config.version);

Readonly with Constructors

Readonly properties are often initialized through constructor parameters, which is useful for values like an ID or creation timestamp that should be fixed for the entire lifetime of the object.

Example: Readonly with Constructors

typescript
class User {
  readonly id: number;
  constructor(id: number) {
    this.id = id; // allowed: assigned inside the constructor
  }
}
console.log(new User(101).id);

Readonly Arrays

TypeScript also provides readonly array types; a readonly array cannot be modified through mutating methods like push or splice, though a new array can still be produced and assigned elsewhere.

Example: Readonly Arrays

typescript
const tags: readonly string[] = ["ts", "types"];
// tags.push("more"); // rejected: readonly arrays block mutation
console.log(tags);

Readonly Method Access

Readonly affects assignment to a property, not reading it — code can freely read and pass around a readonly value, TypeScript only blocks the specific act of writing a new value into it.

Example: Readonly Method Access

typescript
class Point {
  constructor(public readonly x: number) {}
}
const p = new Point(5);
console.log(p.x * 2); // reading is fine

When to Use Readonly

Readonly is appropriate for identifiers, creation dates, configuration values, and other data that should never legitimately change after an object is built, since it turns an accidental mutation into a compile-time error instead of a subtle runtime bug.

Example: When to Use Readonly

typescript
class Event {
  readonly createdAt: Date = new Date();
}
console.log(new Event().createdAt instanceof Date);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.