根据Flow中的对象值定义联合类型 [英] Defining a Union Type from object values in Flow
问题描述
我有一个这样的枚举:
const Filter = {
ALL: 'ALL',
COMPLETED: 'COMPLETED',
UNCOMPLETED: 'UNCOMPLETED'
};
我想做的是声明一个这样的联合类型:
What I'd like to do is declare a union type like this:
type FilterType = Filter.ALL | Filter.COMPLETED | Filter.UNCOMPLETED
但是,这失败了,但是我不确定为什么.根据流程文档:
However, this fails, but I'm not sure why. According to the Flow docs:
创建具有其属性的对象时,可以在Flow中创建密封的对象类型.这些密封的对象将知道您使用它们声明的所有属性以及它们的值的类型.
When you create an object with its properties, you create a sealed object type in Flow. These sealed objects will know all of the properties you declared them with and the types of their values.
因此,如果我没看错的话,Flow应该能够从这些值创建一个类型.相反,它失败并显示:
So, if I'm reading that correctly, Flow should be able to create a type from those values. Instead, it fails with:
Cannot use string as a type because string is a value. To get the type of a value use typeof.
下面是一个流量的链接尝试有可能的解决方案(我不是满意)和其他无法成功使用的方法.
Here's a link to a Flow Try with a possible solution (that I'm not happy with) and other approaches that have unsuccessfully worked.
推荐答案
有一个更简单的解决方案.您可以使用 $Values
实用程序来获取值类型的并集.为了使流解析类型成为文字类型,而不只是string
,应将对象冻结:
There's an easier solution. You can use $Values
utility to get union of value types. And in order to make flow resolve types as literal types instead of just string
the object should be frozen:
const FilterA = Object.freeze({
ALL: 'ALL',
COMPLETED: 'COMPLETED',
UNCOMPLETED: 'UNCOMPLETED'
});
type FilterTypeA = $Values<typeof FilterA>;
let a: FilterTypeA = FilterA.ALL; //OK
a = 'COMPLETED'; //OK
a = 'foo'; //$Expect error: string is incompatible with enum FilterTypeA
此模式适用于 0.60.0版本
这篇关于根据Flow中的对象值定义联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!