所以我使用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
尝试将其细化到数组中的,这是改进它的正确方法到数组类型?
答案 0 :(得分:1)
优化数组的正确方法是使用Array.isArray
函数:
if (Array.isArray(this.props.children)) {
arr = this.props.children;
} else {
arr = [this.props.children];
}