Readonly Properties in TypeScript
In TypeScript, the readonly modifier is used to mark properties as immutable. Once a readonly property is initialized, it cannot be reassigned. This is useful for defining constants or ensuring that certain values remain unchanged throughout the lifecycle of an object.
Defining Readonly Properties
To declare a readonly property, use the readonly keyword before the property name in the class definition:
class Person {
readonly name: string;
readonly birthDate: Date;
constructor(name: string, birthDate: Date) {
this.name = name;
this.birthDate = birthDate;
}
}
const person = new Person("Alice", new Date("1990-01-01"));
// person.name = "Bob"; // Error: Cannot assign to 'name' because it is a read-only property.
console.log(person.name); // Output: Alice
console.log(person.birthDate); // Output: 1990-01-01T00:00:00.000Z
Readonly Arrays
TypeScript also allows you to create readonly arrays using the ReadonlyArray<T> type. This prevents the array from being modified:
let readonlyNumbers: ReadonlyArray = [1, 2, 3, 4, 5];
// readonlyNumbers.push(6); // Error: Property 'push' does not exist on type 'readonly number[]'.
console.log(readonlyNumbers); // Output: [1, 2, 3, 4, 5]
Readonly in Interfaces
You can also use the readonly modifier in interfaces to enforce immutability for certain properties:
interface Point {
readonly x: number;
readonly y: number;
}
let point: Point = { x: 10, y: 20 };
// point.x = 30; // Error: Cannot assign to 'x' because it is a read-only property.
console.log(point); // Output: { x: 10, y: 20 }
Readonly vs. Const
While both readonly and const enforce immutability, they are used in different contexts. const is used for constant variables, while readonly is used for class properties:
// Using const for variables
const MAX_AGE: number = 100;
// MAX_AGE = 101; // Error: Cannot assign to 'MAX_AGE' because it is a constant.
// Using readonly for class properties
class Car {
readonly model: string;
constructor(model: string) {
this.model = model;
}
}
const myCar = new Car("Toyota");
// myCar.model = "Honda"; // Error: Cannot assign to 'model' because it is a read-only property.
Conclusion
The readonly modifier in TypeScript is a powerful tool for enforcing immutability and ensuring that certain properties remain unchanged after initialization. Whether you are defining class properties, arrays, or interface properties, using readonly can help you create more predictable and robust code.
Comments
Post a Comment