Readonly class properties let you create values that cannot be changed after they are set. This helps keep your data safe and predictable.
Readonly class properties in 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.
make that is set when a new Car is created.class Car { readonly make: string; constructor(make: string) { this.make = make; } }
class Point { readonly x: number = 0; readonly y: number = 0; }
id is readonly but name can be changed later.class User { readonly id: number; name: string; constructor(id: number, name: string) { this.id = id; this.name = name; } }
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.
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";
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.
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.