如何告诉Typescript“尝试catch”语句中的错误是包含特定属性的对象而无需使用“任何类型”?
我在 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是未知的
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用谓词!
[游乐场] [2]
You can use a predicate !
[Playground][2]
根据您的目标,有很多方法可以解决此问题。
但这是最简单的:
请注意,Typescript在
catch
子句中的类型规范方面有局限代码>数据属性或任何东西。这是a 打字条游乐场。
There are a lot of ways you could fix this, depending what you're going for.
But this is the simplest:
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 adata
property or anything.Here's the above code in a TypeScript playground.