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
If you need to fix your implementation exactly as you posted, this is the way how to fix it and get it working using type assertions , respectively as I show in the following:
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' exists because you're using type assertion
case 'b':
return console.info('action b: ', (action).b) // property 'b' exists because you're using type assertion
}
}
You can learn more on section "Type Guards and Differentiating Types" of the official documentation: https://www.typescriptlang.org/docs/handbook/advanced-types.html