Readonly (readonly) property in Typescript
(readonly) is a access modifier to mark properties as immutable property.
type User = {
readonly _id: string;
name: string;
email: string;
isActive: boolean;
hobbies: string;
};
Here we have declared a User type that has properties like
_id (readonly) -
readonly _id: string;
name -
name: string;
email -
email: string;
isActive -
isActive: boolean;
among them _id
is a readonly property which means we can not change in other words it is an immutable property
let myUser: User = {
_id: "1234567",
name: "Abir",
email: "a@a.com",
isActive: false,
hobbies: "coding",
};
myUser.email = "a@target.com";
myUser._id = "8473985793425";
Here we are reinitializing the email
but when we are trying to reinitialize the _id
it shows that since it is a read-only property so we cannot assign value to it which is given below ๐๐๐๐
If hobbies
would be an array, then can we push values to the array in case of readonly?
Let's define a new type of user having multiple hobbies
and make it a readonly property
type newUser = {
readonly _id: string;
name: string;
email: string;
isActive: boolean;
readonly hobbies: string[];
};
let User1: newUser = {
_id: "37846823",
name: "Anish Gupta",
email: "anish@gupta.com",
isActive: true
hobbies: ["Painting", "Coding", "Building Apps and websites"],
};
Now if we try to change the original array then it will give an error since the hobbies are readonly type
User1.hobbies = ["Singing", "Dancing"]
But we can push new values to the array by using .push
function which mutates the original array without making an entirely new array even if the array is a readonly
User1.hobbies.push("Reading")
So, the answer is YES then can we push values to the array in case of readonly
Now If we want that nobody can push any values or elements to the readonly
array then how to make the elements inside the array readonly
?
type newUser = {
readonly _id: string;
name: string;
email: string;
isActive: boolean;
readonly hobbies: readonly string[];
};
let User2: newUser = {
_id: "37846823",
name: "Anish Gupta",
email: "anish@gupta.com",
isActive: true
hobbies: ["Painting", "Coding", "Building Apps and websites"],
};
This will make the elements inside the array as readonly
Now we cannot insert or push new elements into the array. Since the array and the elements both are readonly
User2.hobbies.push("Reading")
This will give you this error ๐๐๐๐
In TypeScript, the readonly
property is used to mark properties as immutable, meaning they cannot be changed. When an object is declared with a readonly
property, attempts to modify that property will result in an error. However, if the readonly
property is an array, new values can be added to the array using the .push()
function, even though the array itself remains immutable. To make the elements inside the array also immutable, use the readonly
keyword for the array elements.