TypeScript's readonly properties provide a powerful way to create immutable object properties. They enhance code safety and clarity by preventing accidental modifications to values that should remain constant.
Readonly properties are object properties that can only be assigned a value when an object is first created. After initialization, these properties cannot be changed. This immutability helps prevent bugs and makes code more predictable.
To declare a readonly property, use the readonly
keyword before the property name in an interface or class declaration. Here's a simple example:
interface Point {
readonly x: number;
readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
// p1.x = 5; // Error: Cannot assign to 'x' because it is a read-only property.
In this example, x
and y
are readonly properties. Once set, they cannot be modified.
Readonly properties can also be used in classes. They're particularly useful for properties that should be set only once, typically in the constructor:
class Circle {
readonly radius: number;
constructor(radius: number) {
this.radius = radius;
}
// circumference() method can use radius, but can't modify it
circumference(): number {
return 2 * Math.PI * this.radius;
}
}
const circle = new Circle(5);
console.log(circle.radius); // 5
// circle.radius = 10; // Error: Cannot assign to 'radius' because it is a read-only property.
TypeScript also provides utility types for creating readonly versions of arrays and objects:
const numbers: ReadonlyArray<number> = [1, 2, 3, 4];
// numbers.push(5); // Error: Property 'push' does not exist on type 'readonly number[]'.
const person: Readonly<{ name: string; age: number }> = { name: "Alice", age: 30 };
// person.age = 31; // Error: Cannot assign to 'age' because it is a read-only property.
These utility types provide an additional layer of immutability to your data structures.
To deepen your understanding of TypeScript's type system and immutability features, explore these related topics:
By mastering readonly properties and related concepts, you'll be able to write more robust and maintainable TypeScript code, leveraging the language's powerful type system to prevent errors and improve code quality.