为什么我在这个 Effector 效果订阅者中收到 TypeScript 类型错误?

Why am I getting a TypeScript type error in this Effector effect subscriber?

我正在使用 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' 函数中获取处理程序的 '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"));
      })
    }
  });