Readonly

The readonly keyword is used to define properties whose values can not be changed once they are initialized with a value. The readonly is mostly used with the properties of objects, classes and interfaces.

Syntax:

class className {
public readonly propertyName = value;
}

Features:

  • A property defined using readonly must be assigned at the time of declaration or using the constructor function of the class (if it’s a class property).
  • The value of readonly property can not be re-assigned with a new value.
  • The readonly can be used to create a entire object or specific properties as readonly.

Example: The below code example illustrates the practical implementation of readonly to define properties.

Javascript




// Implementation with classes
class cmpny {
    public readonly name: string =
        "w3wiki";
    public readonly desc: string =
        "A Computer Science Portal.";
}
const myCmpny = new cmpny();
console.log
    (`Company: ${myCmpny.name},
    Description: ${myCmpny.desc}`);
myCmpny.name = "New Company";
myCmpny.desc = "New Description";
console.log
    (`Company: ${myCmpny.name},
    Description: ${myCmpny.desc}`);
 
 
// Implementation with interface and object
interface readonlyInterface {
    readonly crktr_name: string,
    readonly runs: number
}
const obj: readonlyInterface = {
    crktr_name: "Virat Kohli",
    runs: 26000
}
console.log
    (`Cricketer Name: ${obj.crktr_name},
     Runs: ${obj.runs}`);
obj.crktr_name = "Sachin Tendulkar";
obj.runs = 30000;
console.log
    (`Cricketer Name: ${obj.crktr_name},
    Runs: ${obj.runs}`);


Output:

Company: w3wiki, Description: A Computer Science Portal.
Cannot assign to 'name' because it is a read-only property.
Cannot assign to 'desc' because it is a read-only property.
Cricketer Name: Virat Kohli, Runs: 26000
Cannot assign to 'crktr_name' because it is a read-only property.
Cannot assign to 'runs' because it is a read-only property.

Difference Between Const and Readonly in TypeScript

The const and readonly both are used to create the variables and properties that can not be re-assigned once they get initialized by some value. But they are different from each other. Let us discuss the differences between them.

Similar Reads

Const

The const keyword is used to declare the constant variables that can not be re-assigned with a value later. It is mainly applied to the variable declaration....

Readonly

...

Differences between const and readonly in TypeScript

The readonly keyword is used to define properties whose values can not be changed once they are initialized with a value. The readonly is mostly used with the properties of objects, classes and interfaces....