How to implement Nullable feature in es6? I need to support the source code of my previous co-worker, who used too much destructuring feature of es6. Something like this, every where:
dispatch(
loadImports(response.items.map(({ importRecord: { ['import']: importId } }) => importId))
)
In this example, it's possible that I may get TypeError: Cannot read property 'import' of null
error.
I don't want to rewrite the whole destructures to regular conditions. Or if there isn't, how to deal with them, without rewriting?
UPD:
Expected version by co-worker: https://jsbin.com/fesewiy/edit?js,console
Current version: https://jsbin.com/qirixil/edit?js,console
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 . Copied!
Conclusion # The "Cannot destructure property of undefined" error occurs when we try to destructure a property from a value that is equal to undefined . To solve the error provide a fallback when destructuring the property, e.g. const {name} = undefined || {}; .
Each destructured property can have a default value. The default value is used when the property is not present, or has value undefined . It is not used if the property has value null . The default value can be any expression.
To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.
Because you are using map, you need to get some result for each item. The best solution with minimum changes will be to use only one level of destructuring and then filter the array to stay with array of values that are not falsy.
dispatch(
loadImports(response.items
.map(({ importRecord }) => importRecord && importRecord.import)
.filter(v => v)
))
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