0
0
Typescriptprogramming~5 mins

Readonly properties in interfaces in Typescript

Choose your learning style9 modes available
Introduction

Readonly properties help you protect data from being changed by mistake. They make sure some values stay the same after you set them.

When you want to keep some data safe from accidental changes in your program.
When you design objects that should not change after creation, like user IDs or configuration settings.
When you share data between parts of your program and want to avoid bugs from unexpected updates.
Syntax
Typescript
interface InterfaceName {
  readonly propertyName: type;
}

The readonly keyword goes before the property name.

Once set, you cannot assign a new value to a readonly property.

Examples
The id cannot be changed after it is set, but name can be updated.
Typescript
interface User {
  readonly id: number;
  name: string;
}
Both x and y are readonly, so the point's position cannot be changed.
Typescript
interface Point {
  readonly x: number;
  readonly y: number;
}
Sample Program

This program shows a car object with a readonly vin. You can change the model but not the vin.

Typescript
interface Car {
  readonly vin: string;
  model: string;
}

const myCar: Car = { vin: "123ABC", model: "Sedan" };

console.log(myCar.vin); // prints the VIN
myCar.model = "Coupe"; // allowed
// myCar.vin = "456DEF"; // Error: Cannot assign to 'vin' because it is a read-only property

console.log(myCar.model);
OutputSuccess
Important Notes

Readonly only stops changes after the object is created; you must set the value when you create the object.

Readonly works well with interfaces to describe data shapes that should not change.

Summary

Use readonly in interfaces to protect properties from being changed.

This helps avoid bugs by making some data fixed after creation.