带TypeScript的Redux工具包:如何​​正确键入来自异步thunk的返回值

问题描述

我有一个像这样的异步重弹

export const updateIndexingConfig = createAsyncThunk(
  "settings/updateIndexingConfig",(config: UpdateIndexingConfigurationRequest) => {
    return sdkClient.updateIndexingConfiguration(config).promise();
  }
);

如果有更新请求,则更新请求可以返回错误消息。 updateIndexingConfiguration.promise()将返回一个承诺。当用户单击此按钮时,将调度该事件

<Button
  onClick={async () => {
    if (!isFormValid()) return;
    const updateIndexingConfigResponse = await dispatch(
      updateIndexingConfig(constructUpdateIndexingConfigRequest(indexingConfig))
    );
    if(updateIndexingConfigResponse.error) {
      // ... show error banner 
    } else {
      window.location.href = "#/settings/";
    }
  }}
>
  Update
</Button>;

TypeScript编译器在此行if(updateIndexingConfigResponse.error) 上给我这个错误

类型'AsyncThunkAction '。

我认为这是由于SDK没有定义响应类型。但是通过阅读文档,我知道出现问题时响应可能会显示错误消息。所以我很快就做了自己

interface UpdateIndexingConfigurationResponse {
  error?: {
    message: string;
  };
  [key: string]: any;
}

我把它添加到了大块头

export const updateIndexingConfig = createAsyncThunk(
  "settings/updateIndexingConfig",(config: UpdateIndexingConfigurationRequest): UpdateIndexingConfigurationResponse => {
    return sdkClient.updateIndexingConfiguration(config).promise();
  }
);

但是,当我访问分派返回的响应上的error时,编译器仍然对此感到不满意。

类型上不存在属性“错误” 'AsyncThunkAction '。

不确定我在这里缺少什么。在这种情况下如何正确键入响应?

还有一个小问题,TS编译器还在await dispatch(updateIndexingConfig(...))对我大喊

'await'对此表达式的类型没有影响。ts(80007)

但是我知道它确实有效。在这种情况下,它会await

请不要怀疑代码是否有效,或者即使sdkClient.updateIndexingConfiguration(config).promise()返回诺言,我也对其进行了测试,并且知道它可行。只是打字丢失了,这就是我的问题。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)