【问题标题】:Flowtype: Refining arraysFlowtype:精炼数组
【发布时间】:2018-01-11 14:45:07
【问题描述】:

所以我正在使用 React,我有以下代码:

type Props = {
  children: SuperOption | HTMLHrElement | Array<SuperOption | HtmlHrElement>,
 }

然后在我的代码中,我有:

let arr: Array<SuperOption | HtmlHrElement>;
if (this.props.children.length) {
  arr = this.props.children;
} else {
  arr = [this.props.children];
}

这给了我一个流程错误:

HTMLHRElement This type is incompatible with array type
SuperOption This type is incompatible with array type

我认为这是因为 flow 不知道我正在尝试通过执行 this.props.children.length 将其细化为数组,将其细化为数组类型的正确方法是什么?

【问题讨论】:

    标签: reactjs flowtype


    【解决方案1】:

    优化数组的正确方法是使用Array.isArray 函数:

    if (Array.isArray(this.props.children)) {
      arr = this.props.children;
    } else {
      arr = [this.props.children];
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    相关资源
    最近更新 更多