In my last blog post, I introduced the builder pattern in TypeScript and discussed how you can use it to get more accurate types in your code. It was all very abstract, so I thought it might be useful to show another more complex example. If you haven’t read my last blog, I’d recommend it, but I’m the kind of person to ignore that warning so no judgement here!
In this post, I show how the builder pattern can be used to create Reducers in a TypeScript React-Redux app. I discuss the benefits of that approach before walking through the code and explaining what it does at each step.
It’s not perfectly type-safe, but that’s not the goal. Instead, we use the builder pattern to create a type-safe boundary around unsafe code. That way, we can get the best of both worlds - a utility method that is both safe and maintainable.