【问题标题】:Destructuring an undefined object解构未定义的对象
【发布时间】:2021-06-25 16:16:13
【问题描述】:

如果 response 未定义,则在检索其属性 status 时将失败,并出现错误:

TypeError: 无法读取未定义的属性“状态”

const {
  response,
  response: { status },
  request,
  config,
} = error as AxiosError

status 应用默认值不会更改此错误。它仍然会在response 上窒息。

例如

response: { status = 420 },

如何安全地解构它?谢谢。

【问题讨论】:

  • responseundefined(不是null),所以你需要给它一个默认值const { response : {status = 420} = {} } = error

标签: javascript typescript ecmascript-6


【解决方案1】:

我建议避免对具有可选属性的对象使用解构。

如果您的一般情况包含在

const {
  response,
  request,
  config
} = error as AxiosError;

使用可选链接和空值合并的新const 声明更容易跟进:

const status = response?.status ?? 420;

否则你的解构会因为必须包含多个级别的默认值而变得尴尬:

const {
  response,
  response: {
    status = 420
  } = {}, // this could even be { status = ### } and differ from the other default value
  request,
  config
} = error as AxiosError;

【讨论】:

    猜你喜欢
    • 2022-08-23
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 2017-05-26
    • 2020-07-12
    • 2021-08-27
    相关资源
    最近更新 更多