2017-08-26 95 views
1

从流程的文档,我们有这样的:

// @flow 
const countries = { 
    US: "United States", 
    IT: "Italy", 
    FR: "France" 
}; 

type Country = $Keys<typeof countries>; 

const italy: Country = 'IT'; 
const nope: Country = 'nope'; // 'nope' is not a Country 

但是我想要做的

type CountryValue = $Values<typeof countries> 
const italy: CountryValue = 'Italy'; // yes 

这可能吗?

回答

2

您可以使用$Values来排序,尽管您还需要多做一点,因为目前countries中的值仅被检测为任何string。如果你告诉只有特定的值是允许的流量,那么它的工作原理:

type FullNames = "United States" | "Italy"; 

const countries: {[key: string]: FullNames} = { 
    US: "United States", 
    IT: "Italy" 
}; 


const nope: $Values(typeof countries) = 'nope'; // 'nope' is not in the value type 

我猜想这是不是很你想要的东西,因为它需要显式地添加类型,但它是可行的。

+3

Ah darn,谢谢你,看来我必须定义'type FullNames'枚举,所以不妨使用这个吧? – Blagoh

+0

是的,看起来它不会从对象字面值中推断枚举类型。哪种类型是有意义的,因为大多数类型都有对象字面值,所以您不想将其限制为初始值。 – Adam

+2

非常感谢您的帮助,我已经接受了这一点,因为至少它的工作原理和传达的信息是,它应该是该对象中的一个值,并确保该对象中的值来自给定的:) – Blagoh