更好的方法来检查未定义的深层对象流

时间:2018-09-07 15:13:56

标签: javascript flowtype

我正在Java语言中使用Flow类型,并且我有一些深层对象,由于此数据来自api,因此无法定义。而且我发现为了取悦Flow linter,代码变得相当难看。有更好的方法吗?

我的类型可能看起来像这样:

type Top = {   sub?: Sub }

type Sub = {   available?: Available }

type Available = {   start?: string }

代码看起来像这样

function getStart(top) {
  if(top && top.available && top.available.start !== undefined) {
    return top.available.start;
  }
  return null;
}

我试图像这样使用lodash.has,但是下面的代码是流动linter不喜欢的:

import has from "lodash.has"

function getStart(top) {
  if(top && has(top, "top.available.start") {
    return top.available.start;
  }
  return null;
}

是否有更好的方法来处理对流所接受的Javascript深层对象的检查?请记住,上面的示例只是获得一个属性,而在我的代码库中,它们都更深入地获得了更多属性,因此在我看来,这些函数看起来确实很难看。

0 个答案:

没有答案