首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Flowtype类型:细化数组

Flowtype类型:细化数组
EN

Stack Overflow用户
提问于 2018-01-10 17:34:17
回答 1查看 172关注 0票数 1

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

代码语言:javascript
运行
复制
type Props = {
  children: SuperOption | HTMLHrElement | Array<SuperOption | HtmlHrElement>,
 }

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

代码语言:javascript
运行
复制
let arr: Array<SuperOption | HtmlHrElement>;
if (this.props.children.length) {
  arr = this.props.children;
} else {
  arr = [this.props.children];
}

这给了我一个流错误:

代码语言:javascript
运行
复制
HTMLHRElement This type is incompatible with array type
SuperOption This type is incompatible with array type

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-11 06:45:07

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

代码语言:javascript
运行
复制
if (Array.isArray(this.props.children)) {
  arr = this.props.children;
} else {
  arr = [this.props.children];
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48193052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档