How to dispatch an Action or a ThunkAction (in TypeScript, with redux-thunk)?

前端 未结 4 1579
醉话见心
醉话见心 2020-12-17 15:42

Say I have code like so:

import { Action, Dispatch } from \'redux\';
import { ThunkAction } from \'redux-thunk\';

interface StateTree {
  field: string;
}

         


        
4条回答
  •  太阳男子
    2020-12-17 16:09

    I think you are correct in that despite being able to handle both types, typescript cannot work out which overload to use.

    I think the best option for you is to cast back to the desired type when calling dispatch

    function myFunc(action: Action | ThunkAction, 
                    dispatch: Dispatch) {
      if (action instanceof ThunkAction) {
        dispatch(action as ThunkAction);
      } else {
        dispatch(action as Action);
      }
    }
    

    I hope I'm wrong and there is a better way to achieve this.

提交回复
热议问题