| by Arround The Web | No comments

How to Use TypeScript Readonly Utility Type?

TypeScript “Readonly” utility type is one of the useful features that makes a variable or property read-only whose value cannot be changed once it is initialized. It makes a property or field read-only. For example, If the user changes the read-only property value once it has been set then the compiler throws an error i.e. cannot assign to “property-name” because it is a read-only property. This utility type is useful to prevent accidental modification in the property, variable, or field values.

This guide explains the use of the TypeScript “Readonly” utility type.

How to Use TypeScript Readonly Utility Type?

To use TypeScript “Readonly” utility type, specify the “Readonly” keyword with an interface that makes all of its properties read-only.

This section comprises a practical explanation of the “Readonly” utility type.

Example: Applying TypeScript “Readonly” Utility Type

This example applies the TypeScript “Readonly” utility type with an interface to make its properties read-only.

Code

Copy the following lines of code into the “.ts” file available in the TypeScript project directory:

interface User {
 name: string;
}
const user: Readonly<User> = {
 name: "Areej",
};
user.name = "Ali";
console.log(user.name);

In the above code lines:

  • Firstly, the “User” interface is created having one property “name” of the “string” data type.
  • Next, the “user” variable is declared to have a “Readonly” utility type that assigns a value to the “name” property of the “User” Interface.
  • After that, the “user” variable is concatenated with the “name” property to modify its existing value.
  • Lastly, the “console.log()” method is applied to display the “name” property value.

It can be seen that the editor also shows an error while modifying the “name” property value because of the “Readonly” utility type.

Output

tsc main.ts //Compile .ts file

It can be observed that the “.ts” file is not compiled and generates an error i.e. the value of the “name” property cannot be modified because it is a read-only property.

Conclusion

In TypeScript the “Readonly” utility type makes the properties read-only which means the user cannot modify their values. It assigns a new type “Readonly” to the property of an interface. It is useful for the variables or properties whose values do not need to be modified after the initialization process. This guide explained the use of the TypeScript “Readonly” utility type deeply.

Share Button

Source: linuxhint.com

Leave a Reply