【问题标题】:Facebook Flow - how to return a type casted property from deeply nested object?Facebook Flow - 如何从深度嵌套的对象返回类型转换的属性?
【发布时间】:2017-06-05 16:03:03
【问题描述】:

我有一个深度嵌套对象的流类型。我想创建一个提取特定属性的函数,如果该属性存在于该类型的对象上,并且该属性值属于该类型:

在试用流程中可见here

/* @flow */

type DeeplyNested = {
  [string]: string | DeeplyNested
};

function getDogs(deeplyNested: DeeplyNested): ?DeeplyNested {
  return (deeplyNested.dogs: DeeplyNested);
}

let someThingWithDogs = {
  dogs: {
    somethingElse: 'yes'
  }
}

let result = getDogs(someThingWithDogs);

我得到错误:

return (deeplyNested.dogs: DeeplyNested); ^ 字符串。

该类型不兼容return (deeplyNested.dogs: DeeplyNested); ^ 对象类型

有没有办法先检查属性是否属于该类型,然后强制转换并返回该属性?

【问题讨论】:

    标签: javascript reactjs flowtype


    【解决方案1】:

    想通了,只需要检查它是否是一个对象:

    function getDogs(deeplyNested: DeeplyNested): ?DeeplyNested {
      if (typeof deeplyNested.dogs === 'object') return deeplyNested.dogs;
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2016-08-27
    • 2017-04-11
    • 2021-02-04
    相关资源
    最近更新 更多