TypeScript Readonly <Type> Utility Type
Last Updated :
18 Oct, 2023
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
interface Person {
name: string;
age: number;
}
const person: Readonly<Person> = {
name: 'John' ,
age: 30
};
console.log(person);
|
Output:
Example 2: In this example, we will try to change the readonly property of our object. We will get an error.
Javascript
interface Person {
name: string;
age: number;
}
const person: Readonly<Person> = {
name: 'John' ,
age: 30
};
person.name= 'Akshit' ;
console.log(person);
|
Output:
Reference: https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype
Share your thoughts in the comments
Please Login to comment...