Why are these matching unions non-equivalent in Flow?

38 Views Asked by At

Link to Flow Try

From this test it looks like Flow can only check union equivalence at the top-level. I would like to know way to fix this error, preferably without a switch statement with every case of the union accounted for.


type BadRequest = {| __typename: 'BadRequest' |} 
type Forbidden = {| __typename: 'Forbidden' |}

type EitherObject = BadRequest | Forbidden
type EitherLiteral = "BadRequest" | "Forbidden"

const eitherLiteral: EitherLiteral = "BadRequest"

const eitherObject: EitherObject = {__typename: eitherLiteral} // Error?
1

There are 1 best solutions below

0
Ricola On

I know this is probably not the answer you wanted to read, but if you have no control on the EitherObject type definition then you will need some conversion to keep it type safe:

function eitherObjectFromEitherLiteral(eitherLiteral: EitherLiteral) : EitherObject {
    switch(eitherLiteral){
        case 'BadRequest': 
          return { __typename: 'BadRequest'};
        default:
          (eitherLiteral: 'Forbidden')
          return {__typename: 'Forbidden'};
          
    }
}

Flow Try Link