I'm trying to understand how falsy and null values are destructured with default parameters. Here are some examples I've ran:
// #1
const person = { email: '[email protected]' }
const { email = '' } = person
// email is '[email protected]'
// #2
const person = { email: '' }
const { email = '' } = person
// email is ''
// #3
const person = { email: false }
const { email = '' } = person
// email is boolean false. why?!
// #4
const person = { email: null }
const { email = '' } = person
// email is null. why?!
Is there a shortcut I could write to destructure falsy and null values for #3 and #4 so that my email is an empty string?
Default values in destructuring assignement only work if the variables either don't exist or their value is set to undefined . Any other value, including null , false and 0 , bypasses the default values in the destructuring statement. You can combine default values with renaming in the destructuring assignment.
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!
We tried to destructure a property from an undefined value which caused the error. To solve the error, provide a fallback of an empty object when destructuring, or set a default value for the parameter if using functions. Copied! const {name} = undefined || {}; console.
Only undefined
will cause the default initialiser to run in destructuring and function parameter targets. If you want to fall back to your default for all falsy values, use the good old ||
operator instead:
const email = person.email || '';
Or target a mutable variable and use logical OR assignment afterwards:
let { email } = person;
email ||= '';
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