如何键入等待 thunk 调度的结果?

How do I type the result of awaiting a thunk dispatch?

我想等待 thunk 的结果,它 return 是一个异步字符串。我的问题在最后一行——我不知道如何将 cityName 键入为 string

// error, Type 'ThunkAction, AppState, undefined, any>' is not assignable to type 'string'.

代码按预期工作,不幸的是我需要输入 cityName 作为 any

const getCity = (): Thunk<Promise<string>> => async (
  dispatch,
  getState
): Promise<string> => {
  // ...
  const city = await fetchCityApi(query);
  dispatch(setUserCity(city));
  return city;
};

export const getDataUsingCity = (): Thunk<void> => async dispatch => {
  const cityName: string = await dispatch(getCity());
};

我正在为 Thunk 使用包装器,只要我的 Thunk 没有 return 值,它就可以很好地工作:

export type Thunk<R> = ThunkAction<R, AppState, undefined, any>;

这似乎是 redux-thunk 中的一个错误,已修复 within this commit。在提交中使用修改后的 ThunkDispatch 类型可以让上面的代码正常工作。但是,redux-thunk 的新版本自 2018 年 5 月以来尚未发布,这意味着此修复程序未公开提供。

查看相关问题,您也可以通过将 Thunk<R> 的定义更改为

来解决此问题
export type Thunk<R> = ThunkAction<R, AppState, undefined, Action>;

这会强制使用 ThunkDispatch 的正确重载(需要 ThunkAction 的重载)。否则,由于 any TypeScript 无法区分使用两者中的哪一个,因此只会选择第一个(采用普通 Action 的那个)。这也是为什么上面的 PR 解决了这个问题,因为他们重新安排了两个重载以使 TS 默认选择 ThunkAction 变体。