Typescript 如何键入等待thunk分派的结果?

Typescript 如何键入等待thunk分派的结果?,typescript,redux,react-redux,redux-thunk,Typescript,Redux,React Redux,Redux Thunk,我想等待thunk的结果,它异步返回一个字符串。我的问题在最后一行--我不知道如何将cityName键入为string //错误,类型为“ThunkAction,AppState,未定义, 任何>'都不能分配给类型'string' 代码按预期工作,不幸的是我需要键入cityNameasany const getCity = (): Thunk<Promise<string>> => async ( dispatch, getState ): Promise&

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

//错误,类型为“ThunkAction,AppState,未定义, 任何>'都不能分配给类型'string'

代码按预期工作,不幸的是我需要键入
cityName
as
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());
};
const getCity=():Thunk=>async(
派遣,
getState
):承诺=>{
// ...
const city=wait fetchCityApi(查询);
调度(setUserCity(city));
回归城市;
};
export const getDataUsingCity=():Thunk=>async dispatch=>{
const cityName:string=wait dispatch(getCity());
};
我正在使用Thunk的包装器,只要我的Thunk不返回值,它就可以正常工作:

export type Thunk<R> = ThunkAction<R, AppState, undefined, any>;
导出类型Thunk=ThunkAction;

这似乎是
redux thunk
中修复的一个bug。在提交中使用修改后的
ThunkDispatch
类型可以使上述代码正常工作。然而,自2018年5月以来,新版本的redux thunk尚未发布,这意味着此修复程序尚未公开

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

export type Thunk<R> = ThunkAction<R, AppState, undefined, Action>;
导出类型Thunk=ThunkAction;

这将强制使用正确的
ThunkDispatch
(执行
ThunkAction
)重载。否则,由于
any
TypeScript无法消除两个脚本中使用哪一个的歧义,因此只选择第一个脚本(执行普通
操作的脚本)。这也是上述PR修复问题的原因,因为他们重新安排了两个重载,使TS在默认情况下选择
ThunkAction
变量。

您是否尝试过
return
ing调用
dispatch
<代码>退货派送(setUserCity(city))漂亮!非常感谢。这也是一个简单的解决方案。