Create Immutable Object and Array using Typescript
Hi folks, in this article, we will use Typescript to create immutable object and array. Let’s see how simple it is.
We all know that in Typescript we can use const variable declaration to prevent reassigning the value to the variable; this will work with all of the primitive types. (boolean | number | string | symbol | null | undefined)
We can say that iAmAwesome variable is immutable as its value will always be true until the program is terminated.
But how about this case, the variable that has the object as the value?
There is nothing wrong with this; we can change the id and name of the user variable even it’s declared by const.
In the real system, the user will be retrieved from the database and changing the id of it is not what we are expecting. How can we stop others from doing this?
Typescript introduces readonly keyword which we can use for this case.
After using readonly keyword on id field, you will see the error from Typescript service when trying to change its value.
Yup, readonly will prevent properties of the object from being reassigned.
In this case, we assign an array of numbers to numbers variable and use the push method to add an element to it. We all know that we can do this.
How to stop this array from mutation?
Changing the type from number to ReadonlyArray<number> will remove all of the mutable methods (e.g., push, splice, sort, reverse) from numbers variable.
Put it all together
And that’s it, from the help of Typescript service we now get the immutable user object.
*** Update 27/04/2019
type DeepReadonly can be used to change the interface to be the new deep readonly type, it will apply readonly to all properties of the interface. (Deeply)
Thank you for checking this article hope you guys enjoyed it.