我有一个联合类型 Entity
,它由两种不同的类型组成,Door
和 Handle
。属性旋转存在于其中一种子类型中,但不存在于另一种子类型中。这似乎意味着我无法优化该属性,但出现错误 Cannot get entity.rotation because property rotation is missing in
Handle[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
中缺少属性 rotation
1 .
有没有办法改进类型中某个属性存在或不存在的位置?
最佳答案
通过不将 Handle 声明为严格类型,您是在告诉 Flow 它可能包含旋转属性。
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;
}
}
关于javascript - 使用流优化联合类型中的可选属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51242264/