In
TypeScript, you can define read-only properties using the `readonly` modifier. When you mark a property as
`readonly`, it means that once the property is set with a value, it cannot be changed or reassigned.
Here's how you can define read-only properties in TypeScript:
class MyClass {
readonly readOnlyProperty: number;
constructor(value: number) {
this.readOnlyProperty = value;
}
// You can have other methods and properties in the class as well
}
const instance = new MyClass(10);
console.log(instance.readOnlyProperty); // Output: 10
// You cannot reassign the read-only property once it's set
// instance.readOnlyProperty = 20; // This will result in a TypeScript error
In the example above, the `readOnlyProperty` is marked as
`readonly`, and its value is set through the constructor. Once it is set, you cannot modify its value anymore.
Note that the
`readonly` modifier applies only to the property itself, not to the properties of an object that the property might refer to. If the read-only property holds a reference to an object, the properties of that object can still be modified. To make the properties of the object read-only as well, you need to apply the `readonly` modifier to each property within that object.
Here's an example of a read-only property containing a mutable object:
class MyClass {
readonly mutableObject: { value: number };
constructor(value: number) {
this.mutableObject = { value };
}
// You can have other methods and properties in the class as well
}
const instance = new MyClass(10);
console.log(instance.mutableObject.value); // Output: 10
// While the mutableObject itself is read-only, the properties of the object can still be modified
instance.mutableObject.value = 20;
console.log(instance.mutableObject.value); // Output: 20
To make the properties of `mutableObject` also read-only, you would need to use TypeScript's
`Readonly` utility type:
class MyClass {
readonly mutableObject: Readonly<{ value: number }>;
constructor(value: number) {
this.mutableObject = { value };
}
// You can have other methods and properties in the class as well
}
const instance = new MyClass(10);
console.log(instance.mutableObject.value); // Output: 10
// Now the attempt to modify the property will result in a TypeScript error
// instance.mutableObject.value = 20; // TypeScript error: Cannot assign to 'value' because it is a read-only property.
With this approach, both the
`mutableObject` property itself and its properties are read-only, preventing any modifications after instantiation.