Flowtype:精炼数组

时间:2018-01-10 17:34:17

标签: reactjs flowtype

所以我使用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

我认为这是因为流量并不知道我是通过this.props.children.length尝试将其细化到数组中的,这是改进它的正确方法到数组类型?

1 个答案:

答案 0 :(得分:1)

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

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