Redux Typed Actions
An opinionated approach to type actions and their payload in Redux with statically type checking in Typescript. This approach removes the most possible boilerplate of your actions & their creators in React and any other frameworks.
Installation
Let's get started by installing it from npm repository
$ npm install --save-dev redux-typed-actions
or from yarn repository
$ yarn add --dev redux-typed-actions
Usage
Let's do a quick example to see how this approach can improve type checking of redux actions
-
You have an ItemX interface:
feature-x.types.ts -
First we define our actions:
feature-x.actions.ts;;// For this action we will have number as our payload;/*** This action is special, it's called a scenario-like action* It notifies the system with status of a process covering from start to end.* You can get Start/Success/Failure/Cancel from this action generator/creator* There are 4 types that belong respectively to Start/Success/Failure/Cancel* Note: The default type for payload of success and failure is* string so you can skip them like `defineScenarioAction('MyActionName')`*/;// Let's have a symbol action just for fun;Note: You can setup your own suffix for Start/Success/Failure/Cancel of scenario actions as following example:
;// You must set them before defining actionsfactory.setSuffixes; -
Now we dispatch our actions:
feature-x.component.ts;;...// React Redux solution to replace action creators:// Let's define our component's state...// Let's hook the action to redux, and we're done;// All Typescript frameworks:// Dispatching a simple actionstore.dispatchFeatureXAddTicketAction.get100;// Let's start our scenario by dispatching our actionstore.dispatchFeatureXLoadAction.get;// Now we dispatch the success action;dispatchFeatureXLoadAction.success.getpayload;// or simply a failuredispatchFeatureXLoadAction.failure.get'It failed because...'; -
Now let's take a look at our reducers to see how we can type check the payloads:
feature-x.reducers.ts;;; -
If you're fan of
redux-observables
then this part is for you:
feature-x.epics.tsaction$.ofTypeFeatureXLoadAction.type.mapFeatureXLoadAction.castaction // <- from here we will have all the typings right :).switchMapService.mapFeatureXLoadAction.success.getrepos.catchObservable.ofFeatureXLoadAction.failure.get'Oops something went wrong!'; -
That's it