Open In App

What is readonly in Typescript ?

This article will cover the readonly keyword in TypeScript, which is a powerful superset of JavaScript that adds extra features and syntax to the language. The readonly keyword is one of these features, used to set a property or variable as read-only, meaning that the value cannot be changed once it has been initialized. In other words, this keyword makes a property or variable immutable, ensuring that it remains constant throughout the program and cannot be accidentally altered.

By using the readonly keyword, a variable or property in TypeScript can only be assigned a value during initialization or within the constructor of the class. This helps to ensure that the value cannot be changed afterwards, reducing the risk of unintentional modifications that may introduce bugs or unexpected behavior in the code. In other words, readonly provides a way to guarantee that certain values remain constant and unalterable throughout the program.



Syntax:

class MyClass {
    readonly myProperty: MyType;
  
    constructor(myProperty: MyType) {
        this.myProperty = myProperty;
    }
}

Example 1:In this example, we have defined a name property as readonly. This means that the name property can only be set in the constructor and cannot be modified after that. However, the age property is not readonly, which means that it can be modified at any time.






class Person {
      readonly name: string;
      age: number;
  
      constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}
  
const person = new Person('Alice', 30);
person.name = 'Bob'
// Error: Cannot assign to 'name' because 
// it is a read-only property

Output : 

Cannot assign to 'name' because it 
is a read-only property.

Example 2:  In the example above, myProperty is defined as readonly. This means that it can only be set once, which we do in the constructor of the class. Once myProperty has been initialized, it cannot be modified again.  note that readonly only applies to the property itself, not to the value it contains. This means that if the property is an object, the properties of the object can still be modified, even if the property itself is readonly. As shown in the example the Name is can be changed but the object cannot be changed.




class MyClass {
     readonly myObject: { name: string };
      constructor(name: string) {
        this.myObject = { name: name };
  
      }
}
  
const myInstance = new MyClass('Alice');
myInstance.myObject.name = 'Bob'
// Allowed, even though myObject is readonly
  
const myOtherObject = { name: 'Charlie' };
myInstance.myObject = myOtherObject; 
// Error: Cannot assign to 'myObject' because 
// it is a read-only property.

Output: 

Cannot assign to 'myObject' because 
it is a read-only property.

Article Tags :