Open In App

Explain the use of the readonly modifier in TypeScript ?

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The readonly modifier in TypeScript is used to define the class properties or the variables whose values can not be modified again once they are assigned with a value initially. It is a way of expressing the immutability of the code by defining the properties with immutable values and making the code more robust by preventing unintentional changes in the code. You can define the readonly class properties using the readonly keyword, while the const keyword to define the readonly variables. The below syntax shows how you can define readonly properties and variables in TypeScript.

Syntax:

class class_name{
readonly property_name: type = value;
}

const variable_name: type = value;

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads