What is the best way to cast the action
parameter in a redux reducer with typescript? There will be multiple action interfaces that can occur that all extend a base interface with a property type. The extended action interfaces can have more properties that are all different between the action interfaces. Here is an example below:
interface IAction { type: string } interface IActionA extends IAction { a: string } interface IActionB extends IAction { b: string } const reducer = (action: IAction) { switch (action.type) { case 'a': return console.info('action a: ', action.a) // property 'a' does not exists on type IAction case 'b': return console.info('action b: ', action.b) // property 'b' does not exists on type IAction } }
The problem is that action
needs to be cast as a type that has access to both IActionA
and IActionB
so the reducer can use both action.a
and action.a
without throwing an error.
I have several ideas how to work around this issue:
action
to any
.example:
interface IAction { type: string a?: string b?: string }
What is the best way to organize Action/Reducers in typescript? Thank you in advance!
actionTypes - Redux Resource. actionTypes. An object of Redux action types that the resource reducer responds to. Dispatch these from action creators to change the state of your store.
As of React-Redux v8, React-Redux is fully written in TypeScript, and the types are included in the published package. The types also export some helpers to make it easier to write typesafe interfaces between your Redux store and your React components.
Reducers: As we already know, actions only tell what to do, but they don't tell how to do, so reducers are the pure functions that take the current state and action and return the new state and tell the store how to do.
The reducer takes two parameters: state and action . You need to have an initial value so that when Redux calls the reducer for the first time with undefined , it will return the initialState . Then the function uses a switch statement to determine which type of action it's dealing with.
With Typescript 2's Tagged Union Types you can do the following
interface ActionA { type: 'a'; a: string } interface ActionB { type: 'b'; b: string } type Action = ActionA | ActionB; function reducer(action:Action) { switch (action.type) { case 'a': return console.info('action a: ', action.a) case 'b': return console.info('action b: ', action.b) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With