TypeScript: Type System
A brief introduction to “Data Immutability” in TypeScript
In this lesson, we are going to learn a few techniques to make values immutable, both at compile-time and at runtime.
JavaScript is not so strong when it comes to data immutability. Internally, all primitive data types like string
, number
, boolean
etc. are immutable which means you can’t mutate the value once it is set to a variable. You can only assign a new value to a variable and the old one will be garbage collected by the JavaScript engine when the time comes.
That’s not the same story with objects. If you create a plain object using an object literal, you can override the value of a property or add or remove a property to or from an object whenever you want.
var obj = {a: 1}; // define an object
obj.b = 2; // add new property
obj.c = 'hello'; // add new propertyobj.b = 3; // update property value
delete obj.b; // delete property
Objects are by default mutable as shown above and they are passed by reference (but not in a way that operates in other languages). When you assign an object to a variable, the object value doesn’t get copied. JavaScript only assigns a reference of the object to the new…