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
Here's the approach I've taken for this problem:
const reducer = (action: IAction) {
const actionA: IActionA = action as IActionA;
const actionB: IActionB = action as IActionB;
switch (action.type) {
case 'a':
// Only ever use actionA in this context
return console.info('action a: ', actionA.a)
case 'b':
// Only ever use actionB in this context
return console.info('action b: ', actionB.b)
}
}
I'll be the first to admit there's a certain ugliness and hackiness to this approach, but I've actually found it to work pretty well in practice. In particular, I find that it makes the code easy to read and maintain because the action's intent is in the name and that also makes it easy to search for.