[英]Destructuring an undefined object
If response
is undefined, it will fail when retrieving it's property status
with the error:如果
response
未定义,则在检索其属性status
时将失败并显示错误:
TypeError: Cannot read property 'status' of undefined
类型错误:无法读取未定义的属性“状态”
const {
response,
response: { status },
request,
config,
} = error as AxiosError
Applying a default value to status
does not change this error.将默认值应用于
status
不会更改此错误。 It will still choke on response
.它仍然会因
response
窒息。
eg例如
response: { status = 420 },
How can this be safely destructured?这如何安全地解构? Thanks.
谢谢。
I'd recommend avoiding using destructuring for objects that have optional properties.我建议避免对具有可选属性的对象使用解构。
If your general case is covered by如果您的一般情况涵盖在
const {
response,
request,
config
} = error as AxiosError;
It's easier to follow it up with a new const
declaration using optional chaining and null coalescing:使用可选链接和空值合并使用新的
const
声明来跟进它会更容易:
const status = response?.status ?? 420;
Otherwise your destructuring gets awkward by having to include multiple levels of default values:否则,由于必须包含多个级别的默认值,您的解构会变得尴尬:
const {
response,
response: {
status = 420
} = {}, // this could even be { status = ### } and differ from the other default value
request,
config
} = error as AxiosError;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.