我有一个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
由于1中rotation
缺少属性,因此无法获取。Handle
有没有一种方法可以完善类型中某个属性存在或不存在的位置?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句