0
0
Typescriptprogramming~5 mins

Readonly class properties in Typescript

Choose your learning style9 modes available
Introduction

Readonly class properties let you create values that cannot be changed after they are set. This helps keep your data safe and predictable.

When you want to store a value in a class that should never change after the object is created.
When you want to prevent accidental changes to important settings or IDs in your objects.
When you want to make your code easier to understand by showing which values are fixed.
When you want to avoid bugs caused by changing values that should stay constant.
Syntax
Typescript
class ClassName {
  readonly propertyName: Type;

  constructor(value: Type) {
    this.propertyName = value;
  }
}

The readonly keyword makes the property unchangeable after assignment.

You can only set a readonly property when you declare it or inside the constructor.

Examples
This class has a readonly property make that is set when a new Car is created.
Typescript
class Car {
  readonly make: string;

  constructor(make: string) {
    this.make = make;
  }
}
Readonly properties can also be set with default values directly.
Typescript
class Point {
  readonly x: number = 0;
  readonly y: number = 0;
}
Here, id is readonly but name can be changed later.
Typescript
class User {
  readonly id: number;
  name: string;

  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
  }
}
Sample Program

This program creates a Book object with readonly properties title and author. It prints the values. Trying to change title later would cause an error.

Typescript
class Book {
  readonly title: string;
  readonly author: string;

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

const myBook = new Book("The Great Gatsby", "F. Scott Fitzgerald");
console.log(myBook.title);
console.log(myBook.author);

// The following line would cause an error if uncommented:
// myBook.title = "New Title";
OutputSuccess
Important Notes

Readonly properties help prevent bugs by stopping changes to important data.

Trying to change a readonly property outside the constructor will cause a compile-time error.

Readonly is different from const because readonly works on object properties, while const is for variables.

Summary

Readonly class properties keep values fixed after they are set.

They can only be assigned when declared or inside the constructor.

Using readonly makes your code safer and easier to understand.