In TypeScript, the readonly
modifier is used to indicate that a property or variable should not be modified after it has been initialized. This modifier can be applied to class properties, object properties, or function parameters. Here's how you can use the readonly
modifier:
typescriptclass MyClass {
readonly myProperty: number;
constructor(initialValue: number) {
this.myProperty = initialValue;
}
// Error: Cannot assign to 'myProperty' because it is a read-only property.
// Uncommenting the next line will result in a compilation error.
// modifyProperty(newValue: number) {
// this.myProperty = newValue;
// }
}
typescriptconst myObject: { readonly myProperty: string } = {
myProperty: "initialValue",
};
// Error: Cannot assign to 'myProperty' because it is a read-only property.
// Uncommenting the next line will result in a compilation error.
// myObject.myProperty = "newValue";
typescriptfunction printValue(value: readonly number[]) {
// Error: Index signature in type 'readonly number[]' only permits reading.
// Uncommenting the next line will result in a compilation error.
// value.push(42);
console.log(value);
}
const myArray: number[] = [1, 2, 3];
printValue(myArray);
In the above examples, attempting to modify a readonly
property or parameter will result in a compilation error, helping to catch potential bugs related to unintended modifications. Keep in mind that readonly
is a compile-time constraint, and it does not affect the runtime behavior of the code.
Note: The readonly
modifier is different from the const
keyword. readonly
is used for properties and parameters, whereas const
is used for variables.