Typescript Union 和 Type Guard

Typescript Union and Type Guard

使用 RTK 查询 git 从 error 中删除 SerializedError 的最佳方法是什么,就像这里的示例:https://redux-toolkit.js.org/rtk-query/usage/error-handling。还有一个例子是为个别查询输入错误吗?提前致谢

function PostsList() {
  const { data, error } = useGetPostsQuery()
  // error: FetchBaseQueryError | SerializedError | undefined
  // Property 'status' does not exist on type 'FetchBaseQueryError | SerializedError'.
  // How do I check if it's a FetchBaseQueryError before continuing
  return (
    <div>
      {error.status} {JSON.stringify(error.data)}
    </div>
  )
}

最简单的方法是 "status" in error:

{ "status" in error ? <>{error.status} {JSON.stringify(error.data)} </> : undefined }

不支持为单个查询键入错误。不过,这在未来可能会改变。

但通常,有很多与 baseQuery 相关的错误通常会独立于端点响应发生,例如 fetchBaseQuery 解析错误或连接错误。

https://github.com/reduxjs/redux-toolkit/blob/8a5d4bc69beca497625da48954fc1f2621bb0c82/packages/toolkit/src/query/fetchBaseQuery.ts#L61-L99