Read-Only Properties in Interface in TypeScript
Read-only properties are set only once when an object is created. They cannot be changed later. The readonly
keyword is used to declare these properties.
Let's take the IFigure
interface created in the previous lesson. But now let's set the width
property to read-only:
interface IFigure {
height: number;
readonly width: number;
}
Let's create a rectangle
object:
let rectangle: IFigure = {
height: 200,
width: 300
}
Let's change the height:
rectangle.height = 150;
Now let's change the width and see an error, since the width is declared immutable:
rectangle.width = 400; //
Create an interface IUser
in which the property salary
will be read-only.