Open In App

TypeScript Readonly <Type> Utility Type

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

In this article, we are going to learn about Readonly<Type> Utility Type in Typescript. Typescript is a popular programming language used for building scalable and robust applications. One of the features of Typescript is Readonly<Type> Utility Type which is used to create a new type where all properties are readonly, meaning they cannot be modified once assigned a value.

Syntax

interface GFG {
name: string;
age: number;
}
const g: Readonly<GFG> = {
name: 'John',
age: 30
};

Example 1: In this example, we will see how to make a variable Readonly.

 

Javascript




/* Define an interface Person with three
properties: name, age, and address */
interface Person {
    name: string;
    age: number;
}
  
  
/* Declare a Readonly constant called person
with the Person type and assign it a
value of { name: 'John', age: 30 } */
const person: Readonly<Person> = {
    name: 'John',
    age: 30
};
  
/* Log the person constant to the
console to see the output */
console.log(person);


Output:

z2

Example 2: In this example, we will try to change the readonly property of our object. We will get an error.

Javascript




/* Define an interface Person with three
properties: name, age, and address */
interface Person {
    name: string;
    age: number;
}
  
  
/* Declare a Readonly constant called 
person with the Person type and assign 
it a value of { name: 'John', age: 30 } */
const person: Readonly<Person> = {
    name: 'John',
    age: 30
};
  
/* Log the person constant to the
console to see the output */
  
person.name='Akshit';
console.log(person);


Output:

z3

Reference: https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads