yonatanmn
yonatanmn

Reputation: 1600

flow type for "one of object properties"

Flow has keys, that lets you say somthing like:

   const countries = {
    US: "United States",
    IT: "Italy",
    FR: "France"
   };
   type Country = $Keys<typeof countries>;
   const italy: Country = 'IT';

but if I want to have one of the values of Country, I can't find proper way.

I want something like:

function getCountryPopulation(country: $Values<typeof countries>){
...
}
getCountryPopulation(countries.US) //fine
getCountryPopulation("United States") //fine
getCountryPopulation("Canada") //fail

Upvotes: 8

Views: 6142

Answers (2)

ericsoco
ericsoco

Reputation: 26253

$Values landed in `@0.53.1.

Usage, per vkurchatkin:

const MyEnum = {
  foo: 'foo',
  bar: 'bar'
};

type MyEnumT = $Values<typeof MyEnum>;

('baz': MyEnumT); // No error

For more context: https://github.com/facebook/flow/issues/961

Upvotes: 11

hemn
hemn

Reputation: 383

You could do this with some duplicate code:

type Country =  "United States" | "Italy" | "France";

type Countries = {
  US: Country,
  IT: Country,
  FR: Country
}

const countries: Countries = {
  US: "United States",
  IT: "Italy",
  FR: "France"
};

function getCountryPopulation(country: Country) {
  return;
}

getCountryPopulation(countries.US) //fine
getCountryPopulation("United States") //fine
getCountryPopulation("Canada") //fail

Related issue: How to use/define Enums with Flow type checking?

Upvotes: 4

Related Questions