A 2 minute read written by
How to rock and roll with Optional Chaining
Are you being a responsible developer and rocking your undefined-checks to prevent TypeError like this?
const street = customer && customer.address && customer.address.street
That's nice, but you may have noticed it doesn't roll very well. While it's great to protect yourself from type errors, it can get tedious and cumbersome, and it doesn't feel very DRY.
I hope this won't leave you all shook up. Instead, you should read on - it's now or never!
Rock and roll 🕺
The suggested operator looks like this
?., and you can use it to chain undefined-checks:
const street = customer?.address?.street
This will check if both
address is present, and give you the value of
customer does not have the property
address, or if
customer.address does not have the property
street, your variable will receive the value
undefined, and no type errors are thrown.
You can even use this to safely (kinda) run functions or access items in an array:
This will make sure both
api.getCustomer is present, before trying to run
getCustomer. Beware though, that this will still throw a type error if
getCustomer is not a function.
Could I go wrong with this?
Yes, there are some limitations and gotchas to this feature.
The biggest pitfall might be that each operator will only check the current link in the chain:
customer?.address.street // will throw an error if address is undefined customer.address?.street // will throw an error if customer is undefined
Awesome! When can I use it?
Now! While the feature is currently in stage 1, it is of course available as a babel plugin.
I don't know about you, but I just can't help falling in love.