Open In App

TypeScript Object Type readonly Properties

Last Updated : 18 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • MyObject: It is the name of the object type you are defining.
  • propertyName: This is the name of the property that you want to make read-only. It’s followed by the readonly modifier.
  • PropertyType: This is the data type of the property’s value, specifying the expected type of the value.

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.

Javascript




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.

Javascript




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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads