Javascript equivalent of Rails try method

后端 未结 6 795
醉话见心
醉话见心 2021-02-05 01:56

In Rails I can do this:

 x = user.try(:name)

this method returns nil if user is nil else user.name

6条回答
  •  逝去的感伤
    2021-02-05 02:12

    Optional Chaining Operator

    Is a new proposal for ECMAScript.

    It is in an early stage but we can start using it with babel.

    This is the problem:

    const person = {name: 'santiago'}
    let zip = person.address.zip // Cannot read property 'zip' of undefined
    

    This is how it works:

    const person = {name: 'santiago'}
    let zip = person?.address?.zip // undefined
    

    To start using it we need babel alpha 7:

    npm install --save-dev babel-cli@7.0.0-alpha.19
    npm install --save-dev babel-plugin-transform-optional-chaining@^7.0.0-alpha.13.1
    

    And we need to add the plugin to our .babelrc

    {
      "plugins": ["transform-optional-chaining"]
    }
    

    Adam Bene Medium Post which explains how to use it and another use cases

提交回复
热议问题