How to type Redux actions and Redux reducers in TypeScript?

后端 未结 20 2004
旧时难觅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:17

    I might be late to the dance but enum's FTW!

    enum ActionTypes {
      A: 'ANYTHING_HERE_A',
      B: 'ANYTHING_HERE_B',
    }
    
    interface IActionA {
      type: ActionTypes.A;
      a: string;
    }
    
    interface IActionB {
      type: ActionTypes.B;
      b: string;
    }
    
    type IAction = IActionA | IActionB
    
    const reducer = (action: IAction) {
      switch (action.type) {
        case ActionTypes.A:
          return console.info('action a: ', action.a)
    
        case ActionTypes.B:
          return console.info('action b: ', action.b)
        }
    }
    

提交回复
热议问题