Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 658
yonatanmn Avatar asked Apr 18 '17 17:04

yonatanmn


People also ask

How many types of object properties are there?

Objects have two types of properties: data and accessor properties.

What are the options considered as flow objects?

Flow objects can be separated into three. They are events, activities, and gateways.

What are properties in objects?

The basic properties of an object are those items identified by its four-part name (name, type, instance, and version) and also include owner, status, platform, and release.


2 Answers

$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

like image 166
ericsoco Avatar answered Oct 20 '22 00:10

ericsoco


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?

like image 25
hemn Avatar answered Oct 19 '22 23:10

hemn