3
votes

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 inHandle[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

1
FYI you could just check if rotation is a number: if (typeof entity.rotation === 'number') - Aleksey L.

1 Answers

4
votes

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;
  }
}

Flow editor

Flow documentation link