Readonly properties help keep some parts of your data safe by not allowing changes after setting them once.
0
0
Readonly properties in Typescript
Introduction
When you want to make sure a value in an object never changes after creation.
When sharing data between parts of a program and you want to avoid accidental changes.
When creating configuration objects that should stay the same during the program.
When working with data models where some fields must stay constant.
When you want to catch mistakes early by preventing unwanted updates.
Syntax
Typescript
class MyClass { readonly propertyName: type; constructor(value: type) { this.propertyName = value; } }
The readonly keyword goes before the property name.
You can set the value only once, usually in the constructor.
Examples
This class has a readonly
name property set when creating a new person.Typescript
class Person { readonly name: string; constructor(name: string) { this.name = name; } }
This is the correct way to declare a readonly property in an object literal using a type annotation.
Typescript
const obj: { readonly id: number } = { id: 123 };
Readonly properties can also be used in interfaces to describe objects that should not change these fields.
Typescript
interface Car {
readonly make: string;
readonly model: string;
}Sample Program
This program creates a Book with a readonly title. It prints the title. Trying to change the title later will cause an error.
Typescript
class Book { readonly title: string; constructor(title: string) { this.title = title; } } const myBook = new Book("Learn TypeScript"); console.log(myBook.title); // The next line would cause an error if uncommented: // myBook.title = "New Title";
OutputSuccess
Important Notes
Readonly properties can only be assigned once, usually in the constructor or when declared.
Trying to change a readonly property after it is set will cause a compile-time error.
Readonly helps prevent bugs by making data safer and easier to understand.
Summary
Readonly properties keep values from changing after they are set.
Use readonly before a property name in classes or interfaces.
This helps protect important data and avoid mistakes.