When trying to destructure a nested object which could be null, the default value is not being used.
I have accomplished this by destructuring in multiple stages, but would rather do it in a single stage if possible.
const obj = { a: null };
const { a: { b, c } = {} } = obj;
This results in error:Cannot destructure property 'b' of 'undefined' or 'null'
I would expect b and c to be undefined
Destructuring nested objectsIf we need to access an employee's info we can destructure as many levels as it takes to get to our employee object's properties. const { engineers: { 1: { id, name, occupation, }, }, } = employees; Now we have access to all of the second employee object's properties.
Use the logical OR operator to destructure from a nullable object in TypeScript, e.g. const { name, age } = obj || ({} as Person) . The logical OR operator is used to provide a fallback in case the object has a value of null or undefined .
In Arrays: In Arrays, values of corresponding elements get stored in the variables. Example 1: In order to give default values in arrays when applying the destructuring concept in arrays, we need to initialize values with some value. In this way the default values will be assigned to the variables.
For the default value to be used, the value which you are destructuring must be undefined
.
const obj = { a: undefined };
const { a: { b, c } = {} } = obj;
console.log(b, c)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With