检查对象可能为“空”或“未定义”

时间:2020-01-14 10:01:50

标签: javascript node.js typescript

我有这段代码,检查hostel.country.address是否为空,但是

return hostel.country.address &&
               hostel.country.address.internalEmployeeIdentifier !== null ||
               hostel.country.address.externalEmployeeIdentifier !== null;

我遇到此编译问题

hostel.country.address



Object is possibly 'null' or 'undefined'.


- error TS2533: Object is possibly 'null' or 'undefined'.

6 个答案:

答案 0 :(得分:1)

return hostel.country.address &&
               hostel.country.address!.internalEmployeeIdentifier !== null ||
               hostel.country.address!.externalEmployeeIdentifier !== null;

应该工作。

祝你好运

答案 1 :(得分:1)

请尝试

const address = hostel?.country?.address
return address?.internalEmployeeIdentifier !== null || address?.externalEmployeeIdentifier !== null

答案 2 :(得分:0)

添加这样的内容,然后修改返回行以使用它:

function isValid(test) {
    return !(test === null || test === undefined);
}

您的回报可能如下:

return isValid(hostel) && 
       isValid(hostel.country) && 
       isValid(hostel.country.address) &&
       (isValid(hostel.country.address.internalEmployeeIdentifier) ||
        isValid(hostel.country.address.externalEmployeeIdentifier));

答案 3 :(得分:0)

当您具有嵌套属性并且父属性可能存在或不存在时,最好使用一些外部库。这样的事情可以使它变得更简单

const _ = require('lodash');
if(_.get(hostel, 'country.address.externalEmployeeIdentifier')) {
  // do something
}

这样,您就不需要多个&&条件。图书馆会照顾好它。

答案 4 :(得分:0)

另一种方法是使用具有默认值的对象分解。

  const {
    country: {
      address: { internalEmployeeIdentifier, externalEmployeeIdentifier } = {}
    } = {}
  } = hostel || {};

  return (
    internalEmployeeIdentifier !== null || externalEmployeeIdentifier !== null
  );

答案 5 :(得分:0)

您可以使用可选的链接(您应该安装babel插件) 然后您的代码将类似于:

hostel?.country?.address

更多信息,请访问:

https://github.com/tc39/proposal-optional-chaining

https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining

安装: https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining#installation

设置.babelrc

{
  "plugins": ["@babel/plugin-proposal-optional-chaining"]
}