How to type Redux actions and Redux reducers in TypeScript?

后端 未结 20 2059
旧时难觅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条回答
  •  猫巷女王i
    2020-12-13 04:26

    For a relatively simple reducer you could probably just use type guards:

    function isA(action: IAction): action is IActionA {
      return action.type === 'a';
    }
    
    function isB(action: IAction): action is IActionB {
      return action.type === 'b';
    }
    
    function reducer(action: IAction) {
      if (isA(action)) {
        console.info('action a: ', action.a);
      } else if (isB(action)) {
        console.info('action b: ', action.b);
      }
    }
    

提交回复
热议问题