Oved D
Oved D

Reputation: 7442

Flow - intersection with union types error: "Property cannot be accessed on any member of intersection type"

Code can be tried here

I have a type that is an intersection of union types:

type Location = {
  latitude: number,
  longitude: number
} & ({
  locationType: 'country',
  country: string
} | {
  locationType: 'state',
  state:string
})

I have another function that does something based on one of the union types:

const getLocationValue = (location: Location): string => {
  if (location.locationType === 'country')
    return location.country
  else
    return location.state
}

However, this gives me the error:

property country. Property cannot be accessed on any member of intersection type

^ property state. Property cannot be accessed on any member of intersection type

Flow should be able to understand that if locationType is country, then it should have a country property.

What am I doing wrong?

Upvotes: 2

Views: 1256

Answers (1)

Ross Allen
Ross Allen

Reputation: 44880

In order to use a disjoint union Flow needs 2+ types between which to choose. Currently you have defined only a single type: Location. You can split the common values into a sort of "abstract" type and make Location a true type union in order to enable Flow to choose between them. It could look like the following:

type AbstractLocation = {
  latitude: number,
  longitude: number,
}

type CountryLocation = AbstractLocation & {
  country: string,
  locationType: 'country',
}

type StateLocation = AbstractLocation & {
  locationType: 'state',
  state: string,
}

type Location = CountryLocation | StateLocation

Try it: working example on flow.org

Upvotes: 3

Related Questions