bbs*_*son 4 javascript reactjs flowtype
我有一个这样的枚举:
const Filter = {
ALL: 'ALL',
COMPLETED: 'COMPLETED',
UNCOMPLETED: 'UNCOMPLETED'
};
Run Code Online (Sandbox Code Playgroud)
我想做的是声明一个联合类型,如下所示:
type FilterType = Filter.ALL | Filter.COMPLETED | Filter.UNCOMPLETED
Run Code Online (Sandbox Code Playgroud)
但是,这失败了,但是我不确定为什么。根据流文档:
创建具有其属性的对象时,可以在Flow中创建密封的对象类型。这些密封的对象将知道您使用它们声明的所有属性以及它们的值的类型。
因此,如果我没看错的话,Flow应该能够从这些值创建一个类型。相反,它失败并显示:
Cannot use string as a type because string is a value. To get the type of a value use typeof.
这是指向Flow Try的链接,其中包含一个可能的解决方案(我不满意)和其他无法成功工作的方法。
有一个更简单的解决方案。您可以使用$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
Run Code Online (Sandbox Code Playgroud)
此模式自0.60.0版本开始有效
| 归档时间: |
|
| 查看次数: |
1230 次 |
| 最近记录: |