Reputation: 461
If response
is undefined, it will fail when retrieving it's property status
with the error:
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. It will still choke on response
.
e.g.
response: { status = 420 },
How can this be safely destructured? Thanks.
Upvotes: 0
Views: 79
Reputation: 179046
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 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;
Upvotes: 4