How to type Redux actions and Redux reducers in TypeScript?

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

    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

提交回复
热议问题