By default, all the properties declared in the interface are public
but you can make a property read-only by using the readonly
keyword. This means the value of the property cannot be changed once it is initialized. This way we can make a property of an interface immutable.
Let’s create an Animal
interface that has two properties height
and weight
. Next, we will create a dog
object of type Animal
and assign values.
interface Animal {
height: number;
weight: number;
}
let dog: Animal = {
height: 1,
weight: 2,
};
We can re-assign any property after it is initialized. Hence,
console.log(dog); // {height: 1, weight: 2}
dog.height = 3; // allowed
console.log(dog); // {height: 3, weight: 2}
But with readonly modifier, we cannot change the value of the property once it is initialized. Let’s say we want height
property of the interface Animal
to be readonly
.
interface Animal {
readonly height: number;
weight: number;
}
let dog: Animal = {
height: 1,
weight: 2,
};
dog.weight = 5;
console.log(dog); // {height: 1, weight: 5}
dog.height = 3; // Cannot assign to 'height' because it is a read-only property.
As you can see we cannot reassign the value of height
property once it is initialized. Typescript will throw an error, Cannot assign to 'height' because it is a read-only property.