readOnly Option in TypeScript Interface

Last updated on 5 Feb, 2023

When defining the structure of an object using interface keyword, we can specify readonly modifier.

interface Car {
  readonly model: string;

  show(message: string): void;

If any object implements Car interface, there should be a property called model. It should be initialized only once and cannot be changed.

So how it works?

Here is an object that implements the interface Car.

let obj: Car = {
  model: "BMW",
  show: () => {},

Immediately after initialization, if we try to update the model property, TypeScript will throw error.

obj.model = "Audi";

Above line throws below error:

Cannot assign to 'model' because it is a read-only property.
--- ○ ---
Joby Joseph
Web Architect