【问题标题】:Why am I getting a TypeScript type error in this Effector effect subscriber?为什么我在此 Effector 效果订阅者中收到 TypeScript 类型错误?
【发布时间】:2020-07-12 13:31:39
【问题描述】:

我正在使用 React、Typescript、Effector、FetchAPI 等开发前端应用程序。 我做了一个效果器效果来删除我后端的一个项目:

export const deleteItemFX = createEffect({
  handler: (id: string) => {
    return fetch(itemUrl + id, {
      method: "DELETE",
    });
  }
})

现在在我的 React 组件中,我根据文档导入效果并为其“finally”事件添加订阅者:

deleteItemFX.finally.watch(({params, status, result}) => {
    console.log('finally.watch called');
    if (result.ok) {
      result.json().then(() => {
        message.success(t("delete_item.success"));
      })
    }
  });

由于以下类型错误,我的代码无法编译:

Property 'result' does not exist on type '{ status: "done"; params: string; result: Response; } | { status: "fail"; params: string; error: Error; }'.  TS2339

有谁知道我可以做些什么来在“finally.watch”函数中获取处理程序的“结果”?

【问题讨论】:

    标签: typescript typeerror typescript-typings effector


    【解决方案1】:

    问题是,当您将参数解构为watch 时,您试图提取属性result,然后再检查status 是否等于"done" 或"fail"。

    查看错误信息:属性result在类型上不存在:

    { status: "done"; params: string; result: Response; }
    | { status: "fail"; params: string; error: Error; }
    

    这是两个对象类型的union;要从联合中读取属性,该属性必须存在于联合的两边。 result 仅存在于第一种情况,而不存在于第二种情况。因此,在您尝试阅读之前,您需要确保您拥有的数据属于第一种情况。为此,您可以使用 if 语句来优化类型:

    deleteItemFX.finally.watch(response => {
        console.log('finally.watch called');
        if (response.status === "fail") {
            // Handle error here. TypeScript knows that we're in the
            // second case of the union type here, so response.error
            // is available inside this block
            return;
        }
    
        // Now TypeScript knows that we're in the first case of the union,
        // and that response.result exists, so we can read it
        if (response.result.ok) {
          result.json().then(() => {
            message.success(t("delete_item.success"));
          })
        }
      });
    

    【讨论】:

    • 谢谢,就是这样!
    • 好的,我做到了:)
    猜你喜欢
    • 2017-11-23
    • 2018-12-06
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多