How to use the "readonly" modifier in TypeScript



Image not found!!

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:

Class Properties:

typescript
class 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; // } }

Object Properties:

typescript
const 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";

Function Parameters:

typescript
function 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.