How to type Redux actions and Redux reducers in TypeScript?

后端 未结 20 2056
旧时难觅i
旧时难觅i 2020-12-13 03:39

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

20条回答
  •  误落风尘
    2020-12-13 04:21

    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.

提交回复
热议问题