在 Typescript 中检查对象的属性是否为空 [英] Check if an object's properties are null in Typescript
问题描述
在打字稿中,我正在检查对象的属性是否为空,如下所示:
In Typescript I am checking if an object's properties are null as follows:
var addressCountryName = response.address == null
? null
: response.address.country == null ? null : response.address.country.name;
地址和国家都可以为空...我也试过:
Both addresses and country can be null ... I also tried:
var addressCountryName = response.address?.country?.name;
这似乎不起作用......
This does not seem to work ...
是否有最短的方法来检查 null/undefined?
Is there a shortest way to check for null / undefined?
推荐答案
正如其他人提到的,null 合并运算符
仍处于提案阶段,因此您无法使用 访问属性?.
您目前唯一的选择是使用 if 语句或三元组进行深度嵌套,或者考虑使用 lodash 中的 get
方法之类的方法:
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');
如果对象路径的任何部分为空或未定义,则返回 name 或 undefined 的值.
Which will either return the value of name or undefined if any part of the object path was null or undefined.
这是一个使用 lodash 的例子的 CodeSandbox:https://codesandbox.io/s/mm46wkr058
Here's a CodeSandbox with an example of using lodash: https://codesandbox.io/s/mm46wkr058
这篇关于在 Typescript 中检查对象的属性是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!