Javascript 如何获取另一个联合的特定字段的联合
我正试图在我的Redux应用程序上尽可能多地使用类型安全性,但我遇到了这个问题。基本上我有以下类型:Javascript 如何获取另一个联合的特定字段的联合,javascript,redux,flowtype,Javascript,Redux,Flowtype,我正试图在我的Redux应用程序上尽可能多地使用类型安全性,但我遇到了这个问题。基本上我有以下类型: type ActionA = { type: 'A' } type ActionB = { type: 'B' } type Actions = A | B 我想要一个类型ActionType,它是我所有可能的types动作的联合体。i、 e: type ActionType = 'A' | 'B' // <-- How to get this from `Actions` ? 然后
type ActionA = { type: 'A' }
type ActionB = { type: 'B' }
type Actions = A | B
我想要一个类型ActionType
,它是我所有可能的type
s动作的联合体。i、 e:
type ActionType = 'A' | 'B' // <-- How to get this from `Actions` ?
然后我会确定我只能使用有效的操作类型调用
take
。您可以这样建模:
type ActionType = 'A' | 'B'
type Action = { type: ActionType }
type ActionA = { type: 'A' } & Action
type ActionB = { type: 'B' } & Action
function getType(action: Action<*>): * {
return action.type
}
let type1:'B' = getType({type: 'B'}); // OK
let type2:'A' = getType({type: 'B'}); // ERROR
有一些文字重复,但我认为这是不可避免的。此外,通过这种构造,您不会犯错误,因为每个操作都被限制为只有一个有效类型
声明具有如下未知类型的操作本身不是错误:
type ActionC = { type: 'C' } & Action
但它是一种不适合居住的类型,因为'C'
不是有效的操作类型,因此在尝试使用它时会出现编译错误:
let c: ActionC = { type: 'C' }; // ERROR!
另一种解决方案使用泛型:
type ActionType = 'A' | 'B'
type Action<T: ActionType> = { type: T }
// actually you may not want to bother defining these aliases
type ActionA = Action<'A'>
type ActionB = Action<'B'>
注意,*
与任何
不同,并且(与任何
不同)流将能够推断其值,因此您可以执行以下操作:
type ActionType = 'A' | 'B'
type Action = { type: ActionType }
type ActionA = { type: 'A' } & Action
type ActionB = { type: 'B' } & Action
function getType(action: Action<*>): * {
return action.type
}
let type1:'B' = getType({type: 'B'}); // OK
let type2:'A' = getType({type: 'B'}); // ERROR
函数getType(操作:操作):*{
返回操作.type
}
设type1:'B'=getType({type:'B'});//好啊
让type2:'A'=getType({type:'B'});//错误
我认为不可能完全按照你的要求去做。然而,我发布了一些答案,我认为这可能会满足您更广泛的要求。谢谢您的建议!我有这个想法,但我希望我可以避免文字的重复大多数不重复文字的原因在流中并不真正适用。当它们可以进行类型检查时,它们与枚举有很大不同。是的,如果它匹配我试图获得的所有点,我不介意复制。基本上我想要:1)在reducer中过滤动作形状()2)验证字符串文本。第一种方法适用于我目前的方法,但第二种方法在任何地方都很难获得。它目前在创建新操作时有效,但不能阻止我编写takeAction('error\u ACTION')
。理想情况下,我希望捕获if(type==='error\u ACTION')
,但这在今天的flow中似乎不可能实现。实际上,这不起作用,因为flow在使用此方法进行切换时无法正确过滤可能的操作类型(即:)。我猜这是因为“type”是所有类型的并集,所以它不能正确地将动作形状与其类型名称匹配。我也找不到让它与泛型一起工作的方法:(