Reputation: 1284
I have a union type Entity
consisting of two different types, Door
and Handle
. The property rotation exists in one of the sub types, but not the other. This seems to mean that I can't refine on that property, but get the error Cannot get entity.rotation because property rotation is missing in
Handle[1].
I know it's missing, that's why I'm trying to check if it's there.
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;
}
}
Cannot get entity.rotation
because property rotation
is missing in Handle
1.
Is there a way to refine where a property exists or not in the type?
Running example in the flow editor
Upvotes: 3
Views: 464
Reputation: 400
By not declaring Handle as a strict type you are telling Flow that it may contains the rotation properties.
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;
}
}
Upvotes: 4