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

时间:2021-12-07 06:43:29

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

2 个解决方案

#1


4  

$Values landed in `@0.53.1.

美元值落在“@0.53.1。

Usage, per vkurchatkin:

使用,每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

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

#2


2  

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?

相关问题:如何使用/定义带有流类型检查的枚举?

#1


4  

$Values landed in `@0.53.1.

美元值落在“@0.53.1。

Usage, per vkurchatkin:

使用,每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

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

#2


2  

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?

相关问题:如何使用/定义带有流类型检查的枚举?