How to make object properties immutable in TypeScript?


The simple definition of the immutable object property is the properties we can’t modify once we define and initialize the object property.

We can use the const keyword, but we have to initialize the property while creating the property. So, we have to use the readonly keyword to make the property immutable, allowing it to be read-only. So, once we initialize the property, we can’t modify the value of the property.

Syntax

Users can follow the syntax below to use the readonly keyword to make object properties immutable.

interface test {
   readonly property1: boolean;
}
var object: test = {
   property1: false,
};

In the above syntax, property1 of the ‘test’ interface is immutable as it is only read-only, and we can’t change its state outside the object block.

Example

In the example below, the immutableObject contains the key1, key2, and key3. We have used the readonly keyword with the key1 and key2 to make those properties immutable.

We have initialized the immutable properties into the class constructor. If we don’t initialize the immutable object properties in the class constructor, it generates a compilation error.

Also, we can’t change the values of immutable object properties outside the class.

class immutableObject {
   readonly key1: boolean;
   readonly key2: string;
   key3: number;

   constructor(value1: boolean, value2: string, value3: number) {
      this.key1 = value1;
      this.key2 = value2;
      this.key3 = value3;
   }
}

let obj = new immutableObject(true, "hello",5450);
console.log("The object properties are ");
console.log(obj.key1)
console.log(obj.key2)
console.log(obj.key3)

// obj.key1 = false; // modifying the key1 is not allowed as it is immutable

On compiling, it will generate the following JavaScript code −

var immutableObject = /** @class */ (function () {
   function immutableObject(value1, value2, value3){
      this.key1 = value1;
      this.key2 = value2;
      this.key3 = value3;
   }
   return immutableObject;
}());
var obj = new immutableObject(true, "hello", 5450);
console.log("The object properties are ");
console.log(obj.key1);
console.log(obj.key2);
console.log(obj.key3);
// obj.key1 = false; // modifying the key1 is not allowed as it is immutable

Output

The above code will produce the following output −

The object properties are 
true
hello
5450

Example

In this example, we have created the array. The type of the array is ReadonlyArray. Users can try to change the value at any index in the array, and they will get a compilation error as we can’t change the values of immutable properties.

Also, users can try to update the immutable array using the array's push() and pop() methods and observe the compilation error in the output.

let array: ReadonlyArray<number> = [10, 64, 43, 34];
console.log("The value at 1st index is " + array[1]);

// We can't perform push, and pop() operation on the array as it is readonly

// array.push(30);
// array.pop();

On compiling, it will generate the following JavaScript code −

var array = [10, 64, 43, 34];
console.log("The value at 1st index is " + array[1]);

// We can't perform push, and pop() operation on the array as it is readonly

// array.push(30);

// array.pop();

Output

The above code will produce the following output −

The value at 1st index is 64

Example

In TypeScripts, set are the objects. In this example, we have created the set object, and its type is ReadonlySet, which makes the set immutable. Users can see that we can access every element of the set by iterating through the set, but we can’t add or remove elements from the set.

let newSet: ReadonlySet<string> = new Set([
   "Hi!",
   "Hi!",
   "Hello",
   "TypeScript",
   "JavaScript",
]);

console.log("The elements of set are ");
newSet.forEach((ele) => {
   console.log(ele);
});

// adding to the newest is not allowed as it is an immutable object

// newSet.add("string")

On compiling, it will generate the following JavaScript code −

var newSet = new Set([
   "Hi!",
   "Hi!",
   "Hello",
   "TypeScript",
   "JavaScript",
]);
console.log("The elements of set are ");
newSet.forEach(function (ele) {
   console.log(ele);
});
// adding to the newest is not allowed as it is an immutable object

// newSet.add("string")

Output

The above code will produce the following output −

The elements of set are 
Hi!
Hello
TypeScript
JavaScript

Users learned to create immutable objects using the readonly keyword in this tutorial. Also, they learned to create sets and arrays immutable.

The benefit of using the immutable object is that it provides the code's security and improves the code's performance.

Updated on: 20-Jan-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements