“对象属性之一”的流类型

时间:2017-04-18 17:00:04

标签: javascript flowtype

Flow有keys,可以让你说出像:

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

但如果我想拥有values Country之一,我找不到合适的方法。

我想要类似的东西:

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

2 个答案:

答案 0 :(得分:9)

$Values landed in `@0.53.1

用法,per vkurchatkin

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

type MyEnumT = $Values<typeof MyEnum>;

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

更多背景信息: https://github.com/facebook/flow/issues/961

答案 1 :(得分:4)

您可以使用一些重复的代码执行此操作:

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

相关问题:How to use/define Enums with Flow type checking?