【发布时间】:2018-07-09 18:27:13
【问题描述】:
我有一个联合类型Entity,由两种不同的类型组成,Door 和Handle。属性旋转存在于其中一种子类型中,但不存在于其他子类型中。这似乎意味着我无法优化该属性,但得到错误Cannot get entity.rotation because property rotation is missing inHandle[1].
我知道它不见了,所以我试图检查它是否在那里。
type Door = {
id: number,
rotation: number
}
type Handle = {
id: number
}
type Entity = Handle | Door;
const foo = (entity: Entity): number => {
if (entity.rotation) {
return entity.rotation;
} else {
return 2;
}
}
无法获取entity.rotation,因为Handle 1 中缺少属性rotation。
有没有办法细化属性在类型中存在或不存在的位置?
【问题讨论】:
-
仅供参考,您可以检查
rotation是否为number:if (typeof entity.rotation === 'number')
标签: javascript flowtype