How to make object properties immutable in TypeScript ?
In this article, we will try to understand how we could make object properties immutable in TypeScript. JavaScript is a highly dynamic and flexible language, hence making object properties in JavaScript immutable is a little bit typical (although we may implement it somehow using a const data type that doesn’t work always).
So here in TypeScript we will try to implement the immutability of attributes using a keyword called readonly. This keyword could make the object property unchangeable, which is non-alterable but could only be accessed rather than could be modified.
Syntax: Following is the syntax of using the readonly keyword in TypeScript:
class class_name {
readonly property_name : string
...
}
Now that you have some basic idea of implementing this keyword let us see some of the examples in which we could use this readonly keyword.
Example 1: In this example we will be creating a class consisting of several properties and then we will try to read the property values and will also try to update those values and will the result in the console.
Javascript
<script>
class UserDetails {
readonly name: string
readonly city: string
readonly phoneNo: number
constructor(name: string, city: string, phoneNo: number){
this .name = name
this .city = city
this .phoneNo = phoneNo
}
}
let user1 = new UserDetails( "ABCD" , "XYZ" , 1234567890);
let user2 = new UserDetails( "APPLE" , "PQR" , 1269785100);
console.log(user1.city);
console.log(user2.city);
console.log(user1.phoneNo);
</script>
|
Output:
XYZ
PQR
1234567890
Example 2: In this example we will be creating an interface and then further using that interface we will create an object and assign some values to it some being readonly only and then will try to update some values and visualize the result in console.
Javascript
<script>
interface UserDetails {
readonly firstName: string;
lastName: string;
}
let user: UserDetails = {
firstName: "Aman" ,
lastName: "XYZ" ,
};
console.log(user);
user.lastName = "Singla" ;
console.log(user);
</script>
|
Output:
{ firstName: 'Aman', lastName: 'XYZ' }
{ firstName: 'Aman', lastName: 'Singla' }
Reference: https://www.typescriptlang.org/play#example/immutability
Last Updated :
16 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...