【问题标题】:How do I type the result of awaiting a thunk dispatch?如何键入等待 thunk 调度的结果?
【发布时间】:2019-08-07 21:10:59
【问题描述】:

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

// 错误, Type 'ThunkAction, AppState, undefined, any>' 不能分配给类型 '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 不返回值,它就可以很好地工作:

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

【问题讨论】:

  • 您是否在您的dispatch 调用中尝试过returning? return dispatch(setUserCity(city));

标签: typescript redux react-redux redux-thunk


【解决方案1】:

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

查看相关问题,您也可以通过将 Thunk&lt;R&gt; 的定义更改为来解决此问题

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

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

【讨论】:

  • 漂亮!谢谢!如此简单的修复也是如此。
猜你喜欢
  • 2023-03-23
  • 2019-03-05
  • 2016-12-20
  • 2016-05-24
  • 2021-06-26
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多