Redux type-checking without TypeScript/Flow

Nikita Shaposhnik
codeburst
Published in
2 min readMar 25, 2020

--

You might be familiar with a code like:

But, more often than not, todo would contain much more than 3 properties, and then people tend to use smth like:

Of course, really clean code should use some well-thought data structure, more elaborate object nesting, but realistically, you can encounter objects with 30+ properties, and then, typing each property as in first example is tedious. Second approach is actually very bad, new developer has no idea what will or might end up in the store after actions dispatch, but unfortunately, is popular.

Thus, my solution to this would be adding some static-typesque solution, at the very least it can be useful for some quick-and-dirty refactoring. Just add a method to your Utils.js file or some other appropriate place:

And then, use it like this:

Much cleaner, right? This way, you always know what data structure is expected at the end of execution of your reducer. Some might claim that you might just add expected properties in the comments, but then you’re not forced to keep it up to date, and eventually, of course it will drift away from real state of things.

Sometimes you might want to deep clone some of the properties rather than just re-assign them, then you can find more elaborate version of predictableClone to be useful:

And then use it in the very similar manner:

That’s it, hopefully such pattern might be useful in some reducers of your project.

--

--