TypeScript Object Type readonly Properties
In TypeScript, the readonly modifier ensures that a property can be assigned a value only once during initialization and cannot be changed thereafter.
- This immutability helps prevent accidental modifications to object properties, enhancing code reliability.
- You can apply readonly to properties in classes, interfaces, and type aliases.
class ReadonlyExample {
readonly name: string;
constructor(name: string) {
this.name = name;
}
getName(): string {
return this.name;
}
}
const obj = new ReadonlyExample("John");
console.log(obj.getName());
- The name property is marked as readonly, meaning it can only be assigned during object initialization via the constructor.
- The constructor accepts a name parameter and assigns its value to the readonly property.
- The getName method is used to retrieve the value of the name property.
- An instance of the ReadonlyExample class is created with the name "John", and the getName method is called to print the name.
Output:
John
More Examples of TypeScript Object Type readonly Properties
Immutable Point Coordinates
interface Point {
readonly x: number;
readonly y: number;
}
const p1: Point = { x: 10, y: 20 };
console.log(`Point coordinates: (${p1.x}, ${p1.y})`);
// p1.x = 15; // Error: Cannot assign to 'x' because it is a read-only property.
- Defines a Point interface with readonly properties x and y, ensuring the coordinates cannot be modified after initialization.
- Attempts to reassign p1.x will result in a compile-time error, enforcing immutability.
Output:
Point coordinates: (10, 20)
Readonly Array of Numbers
const numbers: ReadonlyArray<number> = [1, 2, 3, 4, 5];
console.log(numbers);
// numbers.push(6); // Error: Property 'push' does not exist on type 'readonly number[]'.
- Creates a ReadonlyArray of numbers, preventing any modification methods like push or pop.
- Ensures the array remains unchanged throughout its lifecycle, promoting data integrity.
Output:
[1, 2, 3, 4, 5]
Readonly Property in a Class
class Car {
readonly make: string;
readonly model: string;
constructor(make: string, model: string) {
this.make = make;
this.model = model;
}
getCarInfo(): string {
return `${this.make} ${this.model}`;
}
}
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.getCarInfo());
// myCar.make = 'Honda'; // Error: Cannot assign to 'make' because it is a read-only property.
- Defines a Car class with readonly properties make and model, set during object instantiation.
- The getCarInfo method returns the car's make and model.
- Attempts to modify myCar.make after creation will result in a compile-time error, preserving the object's state.
Output:
Toyota Corolla
Best Practices for Using TypeScript readonly Properties:
- Initialize During Declaration or Constructor: Assign values to readonly properties either at the point of declaration or within the constructor to ensure they remain immutable.
- Use for Immutable Data: Apply readonly to properties that should not change after initialization, such as configuration settings or constant values, to prevent unintended modifications.
- Combine with Readonly<T> Utility Type: Utilize TypeScript's Readonly<T> utility type to create immutable versions of object types, enhancing code safety and predictability.
TypeScript Object Type readonly Properties - FAQs
Can I modify a readonly property after object creation?
No, readonly properties cannot be modified after they are initialized. Attempting to do so will result in a compile-time error.
What's the difference between readonly and const?
const is used for variables whose values cannot be reassigned, while readonly is applied to properties of objects or classes to prevent their modification after initialization.
Can readonly properties be assigned within methods other than the constructor?
No, readonly properties can only be assigned during their declaration or within the constructor of the class.
Is it possible to have readonly properties in interfaces?
Yes, interfaces can define readonly properties, ensuring that implementing objects cannot modify these properties after initialization.
How does ReadonlyArray<T> differ from Array<T>?
ReadonlyArray<T> creates an array that disallows modification methods like push or splice, ensuring the array cannot be altered after creation