To make a class field readonly or immutable, you can use the readonly
modifier keyword before the class field name in TypeScript.
TL;DR
// a simple class with 2 fields
// and make the `name` field readonly or immutable
// using the `readonly` modifier keyword before field name
class Person {
readonly name = "Anonymous";
age = 1;
}
// create an intance
// of the `Person` class
const person = new Person();
// try to change the value of the `name` field
// this is not allowed ❌.
// Error: Cannot assign to 'name' because it is a read-only property.
person.name = "John";
For example, let's say we have a class called Person
with 2 fields called name
and age
having the values of Anonymous
and 1
respectively like this,
// a simple class with 2 fields
class Person {
name = "Anonymous";
age = 1;
}
In this case, if we create an instance of the Person
class and then use the dot operator (.
) to change the name
field, that value will be changed.
It may look like this,
// a simple class with 2 fields
class Person {
name = "Anonymous";
age = 1;
}
// create an intance
// of the `Person` class
const person = new Person();
// change the value of the `name` field
person.name = "John"; // <- this assignment will change the field value
Now to make the name
field readonly or immutable we can use the readonly
modifier keyword before the field name inside the class like this,
// a simple class with 2 fields
// and make the `name` field readonly or immutable
// using the `readonly` modifier keyword before the field name
class Person {
readonly name = "Anonymous";
age = 1;
}
If we try to change the field value of the Person
instance now, an error will be shown saying that Cannot assign to 'name' because it is a read-only property.
which is what we want to happen.
It may look like this,
// a simple class with 2 fields
// and make the `name` field readonly or immutable
// using the `readonly` modifier keyword before field name
class Person {
readonly name = "Anonymous";
age = 1;
}
// create an intance
// of the `Person` class
const person = new Person();
// try to change the value of the `name` field
// this is not allowed ❌.
// Error: Cannot assign to 'name' because it is a read-only property.
person.name = "John";
We have successfully made a class field readonly in TypeScript. Yay 🥳.
See the above code live in codesandbox.
That's all 😃!