Check if an object's properties are null in Typescript

前端 未结 3 1111
粉色の甜心
粉色の甜心 2020-12-11 22:18

In Typescript I am checking if an object\'s properties are null as follows:

var addressCountryName = response.address == null 
   ? null 
   : response.addre         


        
3条回答
  •  旧巷少年郎
    2020-12-11 22:45

    As others have mentioned the null coalescing operator is still in a proposal stage so you can't access properties using ?. Your only options currently are to do deep nesting with if statements or ternarys or to consider something like the get method from lodash which would let you do:

    let addressCountryName = get(response, 'address.country.name');

    Which will either return the value of name or undefined if any part of the object path was null or undefined.

    Here's a CodeSandbox with an example of using lodash: https://codesandbox.io/s/mm46wkr058

提交回复
热议问题