最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - flow type for "one of object properties" - Stack Overflow

programmeradmin3浏览0评论

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

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
Share Improve this question edited Apr 19, 2017 at 1:24 Nat Mote 4,08619 silver badges30 bronze badges asked Apr 18, 2017 at 17:00 yonatanmnyonatanmn 1,6001 gold badge15 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

$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./facebook/flow/issues/961

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?

发布评论

评论列表(0)

  1. 暂无评论