3 ms·
Maybe I'm missing something but can't you do this for the second one where countryName will be undefined if it's not set? var person = {address:{country:"u
by seanwilson 8y ago
Maybe I'm missing something but can't you do this for the second one where countryName will be undefined if it's not set?
var person = {address:{country:"uk"}}
var {address: {country: countryName}} = person
- vimslayer 8y agoThat would work, but what if the `Person` type's address can also be null? The following would be an error either at runtime or - in the case of TypeScript - at compile time. var person = {address: null} var {address: {country: countryName}} = person
- seanwilson 8y agoHmm, that's annoying behaviour. This doesn't give a runtime error: var [a,b,c] = [1] Either way, I'd highly recommend just using TypeScript.
- vimslayer 8y agoRight, because while b and c will be undefined, they are taken from an existing array, not from null/undefined. This will throw var [a, b, c] = null and this (destructing a nested array) var [[a]] = [] the point of the "elvis" ?. operator is to make accessing properties _of_ optional values or other optional properties easier. "Either way, I'd highly recommend just using TypeScript." Sure, I'd recommend that too, but in this case it "only" helps us by moving the error from runtime to compile-time, nested optional property access remains ugly in the TS world, too. The ?. operator will come to TypeScript as soon as it comes to EcmaScript.