打字稿:是否有一种更干净的方法来检查分层对象结构?

发布于 2025-02-05 21:06:45 字数 397 浏览 2 评论 0 原文

我目前正在null检查一个这样的对象结构:

if (error.response && error.response.data && error.response.data.errorMessage)
{
  // Do stuff
}

我真正想做的就是null检查最深的变量 error.response.data.errormessage ,但是因为我想避免null指针异常。检查我必须先检查 error.Response ,然后 error.response.data

有什么干净的方法可以做到吗?我想,随着您想越来越深入地查询层次结构,可能会变得很混乱。

提前致谢!

I'm currently null checking an object structure like so:

if (error.response && error.response.data && error.response.data.errorMessage)
{
  // Do stuff
}

All I really want to do is null check the deepest variable error.response.data.errorMessage, but because I want to avoid null pointer exceptions in the check I have to first check error.response, and then error.response.data.

Is there a cleaner way to do this? I imagine as you want to query deeper and deeper into the hierarchy it can get quite messy.

Thanks in advance!

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

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

发布评论

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

评论(1

记忆里有你的影子 2025-02-12 21:06:45

您可以使用

if (error.response?.data?.errorMessage) {
  // Do stuff
}

You can use optional chaining:

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