首页 > 解决方案 > Typescript:如何在 Redux 中键入 Dispatch

问题描述

例如我想在dispatch: any这里删除:

export const fetchAllAssets = () => (dispatch: any) => {
  dispatch(actionGetAllAssets);
  return fetchAll([getPrices(), getAvailableSupply()]).then((responses) =>
    dispatch(actionSetAllAssets(formatAssets(responses))));
}

我在上面调度了 2 个动作,actionsGetAllAssets并且actionsSetAllassets.

以下是两者的接口和 actionCreators:

// Interfaces
interface IActions {
  GET_ALL_ASSETS: string;
  SET_ALL_ASSETS: string;
  GET_MARKET_PRICES: string;
  SET_MARKET_PRICES: string;
  ADD_COIN_PORTFOLIO: string;
  ADD_COINS_PORTFOLIO: string;
  UPDATE_COIN_PORTFOLIO: string;
  REMOVE_COIN_PORTFOLIO: string;
} 

interface IGetAllAssets {
  type: IActions['GET_ALL_ASSETS'];
  loading: boolean;
}

interface ISetAllAssets {
  type: IActions['SET_ALL_ASSETS'];
  assets: IAsset[];
  loading: boolean;
}

// ACTION CREATORS
const actionGetAllAssets = () => ({
  type: Actions.GET_ALL_ASSETS,
  loading: true
});

const actionSetAllAssets = (data: any) => ({
  type: Actions.SET_ALL_ASSETS,
  assets: data,
  loading: false
});

所以我尝试了以下方法:

export const fetchAllAssets = () => (dispatch: IGetAllAssets | ISetAllAssets) => {
  console.log('fetchAllAssets', dispatch);
  dispatch(actionGetAllAssets);
  return fetchAll([getPrices(), getAvailableSupply()]).then((responses) =>
    dispatch(actionSetAllAssets(formatAssets(responses))));
}

但是它会产生这个 Typescript 错误:

无法调用其类型缺少调用签名的表达式。输入'IGetAllAssets | ISetAllAssets' 没有兼容的调用 signatures.ts(2349)

想法?或者是否有不同的方式来输入调度事件?

标签: javascripttypescriptreduxreact-reduxdispatch

解决方案


Redux 类型有一个Dispatch<A>你可以使用的泛型类型,其中A是 action 的类型。

export const fetchAllAssets = () => (dispatch: Dispatch<IGetAllAssets | ISetAllAssets>) => {
  // ...
}

推荐阅读