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
答案 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
答案 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