Destructuring Assignment and Zero Combining

For special purposes in CoffeeScript, you can use the existential operator:

name = obj?.props?.name

This leads to a rather long block of code that checks that objit is propsdefined.

name = typeof obj !== "undefined" && obj !== null ? 
    (_ref2 = obj.props) != null ?
    _ref2.name : void 0 : void 0;

Consider a more complex, destructive purpose:

{name: name, emails: [primary], age: age} = Person.get(id)

If the object does not contain a property emails, this code will call TypeError. Is there a way to use an existential operator with such destructuring assignments?

This is the best alternative that I have so far:

{name: name, emails: emails, age: age} = Person.get(id)
primary = emails?[0]
+4
source share
2 answers

In ES6, you can do this:

const {name: name, emails: [primary] = [], age: age} = Person.get(id)

If Person.get(id)returns an empty object, it primarywill be undefined(no TypeError).

CoffeeScript 2 , http://coffeescript.org/v2/#try

+1

. , , .

0

All Articles