Immutability
JavaScript defines two overarching groups of data types:
Primitives
: low-level values that are immutable (e.g. strings, numbers, booleans etc.)References
: collections of properties, representing identifiable heap memory, that are mutable (e.g. objects, arrays, Map etc.)
Mutable References
Let’s contrast the behavior of primitives with references. Let’s declare an object with a couple of properties:
Given that JavaScript objects are mutable, we can change its existing properties and add new ones:
Unlike primitives, objects can be directly mutated without being replaced by a new reference. We can prove this by sharing a single object across two declarations:
NGXS provides pseudo-immutable Objects.
Immutable Type
Immutable
- There are no built-in utility types to handle deep immutability, but given that TypeScript introduces better support for recursive types by deferring their resolution, we can now express an infinitely recursive type to denote properties as readonly across the entire depth of an object.
What are the benefits?
Thus, the developer will not be able to make his own mistake. If he mutates the state directly or use mutational methods. If you need to use states for set input property:
Casting to mutable
However, if you really need to cast to mutable, you can do this in several ways:
Into state
:
or Into template
without creating mutableState$
:
State operators
To use state operators, you must specify the exact return type:
Last updated
Was this helpful?