redux-typed-action
Typesafely create actions and reducers for Redux in TypeScript.
Using this library possibly makes modules Ducks-like.
Install
npm install redux-typed-action --save
Usage
Create action creators and a reducer using createAction
and createReducer
provided by redux-typed-action.
console.logcounterActions.increment // { type: 'INCREMENT' }console.logcounterActions.add100 // { type: 'ADD', payload: 100 }// counterActions.increment(100) // compile error: payload of increment() requires undefined// counterActions.add('100') // compile error: payload of add() requires number
And use them normally with combineReducers
, createStore
, bindActionCreators
of Redux.
console.logstore.getState // { counter: 0 }actions.counter.incrementconsole.logstore.getState // { counter: 1 }actions.counter.add100console.logstore.getState // { counter: 101 } // actions.counter.increment(100) // compile error: payload of increment() requires undefined// actions.counter.add('100') // compile error: payload of add() requires number
Why?
Using Redux requires some boilerplate code.
In TypeScript, redundant code increases.
The reducer have to identify the type of the action by the type
property.
Therefore, each action should be typed explicitly and that type will be shared with the action creator and the reducer.
// cf. https://stackoverflow.com/questions/35482241/how-to-type-redux-actions-and-redux-reducers-in-typescript
But it is painful to define type for each action.
This library offers you to declare type of payload as an inline type literal and use that payload immediately once.
The created action creator requires a parameter of the type declared above. The compiler and IDE will help you. I think this way is safe, efficient and easy to maintain.
API
createAction<State, Payload, Metadata>(type: string, handler: (State, Payload, Metadata) => State, metadataFactory: Payload => Metadata) => ActionCreator<State, Payload, Metadata>
Returns a new action creator.
createReducer<State>(actions: Record<string, ActionCreator<State, any, any>>, initialState: State) => Reducer<State>
Returns a new reducer.