我有一个像这样的枚举:
const Filter = {
ALL: 'ALL',
COMPLETED: 'COMPLETED',
UNCOMPLETED: 'UNCOMPLETED'
};
我想做的是声明一个这样的联合类型:
type FilterType = Filter.ALL | Filter.COMPLETED | Filter.UNCOMPLETED
但是,这失败了,但是我不确定为什么。根据{{3}}:
使用属性创建对象时,将在Flow中创建密封的对象类型。这些密封的对象将知道您使用它们声明的所有属性以及它们的值的类型。
因此,如果我没看错的话,Flow应该能够从这些值创建类型。相反,它失败并显示:
Cannot use string as a type because string is a value. To get the type of a value use typeof.
以下是指向Flow docs的链接,其中包含可能的解决方案(我不满意)和其他方法均无法成功使用。
答案 0 :(得分:3)
有一个更简单的解决方案。您可以使用$Values
实用程序来获取值类型的并集。为了使流解析类型成为文字类型而不是string
,应将对象冻结:
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 version
开始有效