If like me you also believe everything should be immutable, you’ll be happy to see what Typescript 3.4 brings with it.
ReadonlyArray, which helps us prevent array mutations at compile time.
This is just one of the many reasons why Redux was so popular in the first place. Mutations cause all sorts of issues in our code, and they also happen to be quite difficult bugs to track down.
I see this happening a lot in Angular teams: an array gets passed down to a component, and the child component happens to be sorting this array: what happens? the array mutation propagates all the way up to the parent.
Consider the snippet below:
These sort of mistakes cost me hours and hours during my career, often mistakes made by me.
But lately, these are bugs I have fixed for code that was already there, as I finally learned how to **never mutate an object or an array. **
The thing is, sometimes it can still happen.
How does Typescript’s
ReadonlyArray help us in minimizing this sort of errors? Check the image below:
As you can see, the compiler warns us there’s a mistake, as the interface
ReadonlyArray does not contain the method
As weird as it sounds, I love being told I am making a mistake. It’s why I like Typescript so much.
Let’s see what the compiler tells us about different operations on read-only arrays:
As you can see, reverse, sort, splice, push are all methods that mutate the array — so we better avoid using them.
Other methods, such as
reduce, etc. are immutable, and should always be preferred.
Do your future-self, or whoever is going to pick up your code one day, a small favour: use