"对象属性之一"的流类型

yon*_*nmn 5 javascript flowtype

流量keys,让你说的像:

   const countries = {
    US: "United States",
    IT: "Italy",
    FR: "France"
   };
   type Country = $Keys<typeof countries>;
   const italy: Country = 'IT';
Run Code Online (Sandbox Code Playgroud)

但如果我想有一个valuesCountry,我无法找到正确的方法.

我想要的东西:

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

eri*_*oco 9

$Values 降落在`@0.53.1.

用法,每vkurchatkin:

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

type MyEnumT = $Values<typeof MyEnum>;

('baz': MyEnumT); // No error
Run Code Online (Sandbox Code Playgroud)

有关更多上下文:https: //github.com/facebook/flow/issues/961

  • 我对这个问题的理解是,当字符串不是对象中的值时,他正在寻找它失败。这里正在过去。我的理解是`MyEnumT` 本质上变成了`string` 类型。 (2认同)