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.

Redux Reducers

I’ll assume you have used Redux before, but here’s a quick primer if not:

Redux is a state management library that’s usually used with React. In Redux, there is a single global ‘store’ which contains the current state of the website. The store is updated by dispatching an ‘action’ onto the store. Each action has two properties, type and payload. Attach a ‘reducer’ to the store to define how the state should change when an action is received. Each reducer contains a number of cases, where each case handles a given type of action.

For a full explanation of those concepts and the terminology, read the official documentation.

Redux Type Safety

For the remainder of this post, we will be using Redux Toolkit, the official recommended way to develop Redux apps. However, you could easily tweak this code to work in a plain Redux project that doesn’t use Redux Toolkit.

In Redux Toolkit, you are expected to use ‘action creators’ rather than writing your actions as object literals. They are important later, so let’s start by writing a couple of action creators. I’ll assume our app is a counter, meaning the state is a number and we have two actions:

const incrementAction = createAction("increment");
const setAction = createAction<number, "set">("set");

Now that we have our actions, there are two ways to create a reducer that handles them:

  1. From a map of action types to handlers
  2. Using a builder

#swaterman #tech #redux

Better Redux Reducers with TypeScript Builders
1.95 GEEK