redux-ts-actions
Type-safe action creators and reducers for redux. Action creators infer input and payload types and reducers infer payload type based on respective action creators. Requires TypeScript 3+.
Example Usage
; // Action Creators;; // Users Reducer ;; ; // Use the reducer:.reducereducer, undefined;
API
createAction
This function creates an action creator. It optionally accepts a payload customizer function. The payload type of the resulting action creator and the arguments the action creator accepts are inferred from the payload creator function.
; // Fully-implicit typing;createUser'Ken', 15; // Compiles and returns an object with a known shape of { type: 'user/CREATE_USER', payload?: User }createUser'Ken', false; // Fails to compile. `boolean` is not assignable to `number`. // Identity typing;createUser; // Compiles and returns the same object as beforecreateUser; // Fails to compile. `boolean` is not assignable to `number`. // Fully-explicit typing;createUser'Ken', 15; // Compiles and returns an object with a known shape of { type: 'user/CREATE_USER', payload?: { name, followers }}createUser'Ken', false; // Fails to compile. `boolean` is not assignable to `number`. // No Payload;increment; // Creates an action with no payload // Error Handling// All of the above action creators can accept an Error as their only argument.// Payload customizers will not be called and the resulting actions will have// their `error` property set to `true` and their payload will be the error// object.createUsernew Error'Foo'; // { type: 'user/CREATE_USER', payload?: Error, error: true }
handleAction
This function creates a type-safe reducer given an action creator and a reducer
function. The state argument must be typed (unless this is used in the context
of reduceReducers
documented below) but the action argument will be inferred
based on the action creator.
; ; // Or ;
Flux Standard Actions
A Note AboutThe payload
property on Flux Standard Actions is optional. In
TypeScript you can work with these actions in one of two ways:
; // Method 2 also works with destructuring:;
reduceReducers
This function composes reducers together into a single reducer. It takes an array of reducer functions and an optional default state. If you specify a type then you don't need to specify state types for any child reducers.
; ;;; // Passing a type to `reduceReducers` allows everything below to be typesafe: ;
License
MIT