如何告诉Typescript“尝试catch”语句中的错误是包含特定属性的对象而无需使用“任何类型”?

发布于 2025-02-12 14:14:27 字数 721 浏览 1 评论 0 原文

我在 console.log 语句下面遇到一个错误:

try {
    // ...
} catch(e) {
    if (typeof e === "object" && e !== null && e.hasOwnProperty("data")) {
        console.log(e.data);
    }
}

当我尝试访问 e.data 时,我会收到以下typescript错误:

属性'data'dim在类型“ Object”中不存在(2339)

i明确检查 e 是否具有 data 的属性,虽然对吗?因此,我不明白为什么Typescript在e上说数据不存在。

如何正确告诉TypescriptE E具有数据属性? 我知道我可以将错误作为任何类型的类型施加,但是我认为这是不错的做法,并且想避免使用任何。我的工作不允许施放代码库中任何地方的任何

下面我错误的屏幕截图:

e是未知的

I get an error in the console.log statement below:

try {
    // ...
} catch(e) {
    if (typeof e === "object" && e !== null && e.hasOwnProperty("data")) {
        console.log(e.data);
    }
}

when I try to access e.data, I get the following TypeScript error:

Property 'data' does not exist on type 'object'.ts(2339)

I explicitly check if e has a property of data though right? So I'm not understanding why TypeScript is saying data doesn't exist on e.

How can I tell TypeScript properly that e has a property of data?
I know I can cast the error as an any type, but I don't think this is good practice and would like to refrain from using any if possible. My work does not allow for casting any anywhere in the codebase.

screenshots of my errors below:

e is of unknown

typescript error

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

许仙没带伞 2025-02-19 14:14:27

您可以使用谓词

try {
    // ...
} catch (e) {
    if (hasData(e)) {
        console.log(e.data);
    }
}

function hasData(object: unknown): object is { data: unknown } {
    return (typeof object === "object" && object?.hasOwnProperty("data")) ?? false
}

[游乐场] [2]

You can use a predicate !

try {
    // ...
} catch (e) {
    if (hasData(e)) {
        console.log(e.data);
    }
}

function hasData(object: unknown): object is { data: unknown } {
    return (typeof object === "object" && object?.hasOwnProperty("data")) ?? false
}

[Playground][2]

寄意 2025-02-19 14:14:27

根据您的目标,有很多方法可以解决此问题。

但这是最简单的:

try {
    // ...
} catch(e: any) {
    if (typeof e === "object" && e !== null && e.data) {
        console.log(e.data);
    }
}

请注意,Typescript在 catch 子句中的类型规范方面有局限代码>数据属性或任何东西。

这是a 打字条游乐场。

There are a lot of ways you could fix this, depending what you're going for.

But this is the simplest:

try {
    // ...
} catch(e: any) {
    if (typeof e === "object" && e !== null && e.data) {
        console.log(e.data);
    }
}

Note that TypeScript has limitations surrounding what you can do in terms of type specification in a catch clause, so you can't do something more complicated like declare an error type containing a data property or anything.

Here's the above code in a TypeScript playground.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文