Open In App

TypeScript Object Type readonly Properties

In TypeScript, an Object Type with readonly properties specifies that the properties of the object cannot be modified after their initial assignment, ensuring immutability and preventing accidental changes to the object’s values.

Syntax

type MyObject = {
     readonly propertyName: PropertyType;
};

Parameters

Example 1: In this example, Point is an object type with two read-only properties, x and y. When we attempt to modify the x property, TypeScript raises an error because it’s read-only. In the case of attempting to modify read-only properties, it will result in a TypeScript error.






type Point = {
    readonly x: number;
    readonly y: number;
};
  
const point: Point = { x: 10, y: 20 };
console.log(point)
  
// Attempting to modify read-only 
// properties will result in a TypeScript error
  
// Error: Cannot assign to 'x' because 
// it is a read-only property.
// point.x = 30;

Output:

{ x: 10, y: 20 }

Example 2: In this example, Acc is an object type with three read-only properties: name, place, and number. When we attempt to modify the place property, TypeScript raises an error because it’s read-only. Here, also, in the case of attempting to modify read-only properties, it will result in a TypeScript error.






type Account = {
    readonly name: string;
    readonly place: string;
    readonly contact: number;
};
  
const acc: Account = 
    { name: "GeeksforGeeks"
      place: "Noida"
      contact: 7838223507 };
console.log(acc)
  
// Attempting to modify read-only properties
// will result in a TypeScript error
  
// Error: Cannot assign to 'place'
// because it is a read-only property.
// acc.place = Gurgaon;

Output:

{ name: 'GeeksforGeeks', place: 'Noida', contact: 7838223507 }

Reference: https://www.typescriptlang.org/docs/handbook/2/objects.html#readonly-properties


Article Tags :