如何使用typescript确定属性是否为null?
首先,我将httpRequest请求url并获取一些数据如何使用typescript确定属性是否为null?,typescript,Typescript,首先,我将httpRequest请求url并获取一些数据 { "data": { "user": { "name": "john", "other": [{ "a": 1, "b": 3 }] } } } 我想确定这个ArrayTher是否为null,所以我会 if(data!=null && d
{
"data": {
"user": {
"name": "john",
"other": [{
"a": 1,
"b": 3
}]
}
}
}
我想确定这个ArrayTher是否为null,所以我会
if(data!=null && data.user!=null && data.user.other!=null && data.user.other.length>0)
我发现写很多无用的代码既乏味又麻烦。
有简单的方法吗?
在c中,我将:
if(data?.user?.other?.Any()==true)
{
//dosomething
}
如何使用typescript编写它?如果您是on或更高级别的,您可以使用可选的链接,这与您在c中使用的非常类似。可选链接将:
如果沿data?user?other?长度的任何步骤为null或未定义,则此代码将被短路并解析为未定义。然后undefined>0将导致false。如果您处于on或更高级别,您可以使用可选链接,这与您在c中使用的非常类似。可选链接将:
如果沿data?user?other?长度的任何步骤为null或未定义,则此代码将被短路并解析为未定义。然后undefined>0将导致false。如果版本低于3.7,您将使用您提到的那种单调乏味的方式。或者使用一个实用程序库来简化它,比如ramda,尽管这些函数通常不能强制执行类型。如果版本在3.7之前,您将使用您提到的单调乏味的方式。或者使用一个实用程序库来简化它,比如ramda,尽管这些函数通常不能强制类型。
if (data?.user?.other?.length > 0) {