英文:
How to remove 'loginError.data' is of type 'unknown' error?
问题
我对TypeScript还很陌生,正在尝试使用`nextjs`和`rtk query`以及`antd`。但在尝试访问`useLoginMutation`中的`error`属性`error.data.message`时,它显示`error.data`的类型为`unknown`。
到目前为止,我尝试了使用类型守卫函数。
```typescript
import { FetchBaseQueryError } from "@reduxjs/toolkit/dist/query";
export default function isFetchBaseQueryError(
error: unknown
): error is FetchBaseQueryError {
return typeof error === "object" && error != null && "status" in error;
}
if (!isLoginLoading && error) {
if (isFetchBaseQueryError(error)) {
notification.error({
message: "登录失败",
description: error.data.message, // 这行代码导致错误
});
}
}
<details>
<summary>英文:</summary>
I am new to typescript and trying out `nextjs` and `rtk query` with `antd`. By when trying to access `error` in `useLoginMutation` inside properties `error.data.message` , it shows `error.data` is type `unknown` .
What I have tried so far is I used a type guard function.
import { FetchBaseQueryError } from "@reduxjs/toolkit/dist/query";
export default function isFetchBaseQueryError(
error: unknown
): error is FetchBaseQueryError {
return typeof error === "object" && error != null && "status" in error;
}
if (!isLoginLoading && error) {
if (isFetchBaseQueryError(error)) {
notification.error({
message: "Login Failed",
description: error.data.message, // this line is causing error
});
}
}
</details>
# 答案1
**得分**: 2
```ts
import get from 'lodash/get'
function isFetchBaseQueryError(
error: unknown
): error is FetchBaseQueryError & { data: { message: string } } {
return (
typeof error === "object" &&
error != null &&
"status" in error &&
"data" in error &&
!!get(error, "data.message") // 确保 data.message 存在
);
}
const error = { data: { message: "message" }, status: "403" };
if (isFetchBaseQueryError(error)) {
console.log(error.data.message);
}
const error1 = { status: "403" };
if (isFetchBaseQueryError(error1)) {
console.log(error.data.message);
} else {
console.log("data.message not defined");
}
英文:
Take a look at this one: https://codesandbox.io/s/icy-fire-hsjoqx?file=/src/App.tsx
import get from 'lodash/get'
function isFetchBaseQueryError(
error: unknown
): error is FetchBaseQueryError & { data: { message: string } } {
return (
typeof error === "object" &&
error != null &&
"status" in error &&
"data" in error &&
!!get(error, "data.message") // make sure data.message exists
);
}
const error = { data: { message: "message" }, status: "403" };
if (isFetchBaseQueryError(error)) {
console.log(error.data.message);
}
const error1 = { status: "403" };
if (isFetchBaseQueryError(error1)) {
console.log(error.data.message);
} else {
console.log("data.message not defined");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论