Redux 如何避免在流中使用文字字符串来缩小不相交的并集
我在网上找到的所有缩小flowtype中不相交并集的示例都使用字符串文字,如。我想知道是否有一种方法可以检查枚举中的值,如:Redux 如何避免在流中使用文字字符串来缩小不相交的并集,redux,flowtype,Redux,Flowtype,我在网上找到的所有缩小flowtype中不相交并集的示例都使用字符串文字,如。我想知道是否有一种方法可以检查枚举中的值,如: const ACTION_A = 'LITERAL_STRING_A'; const ACTION_B = 'LITERAL_STRING_B'; type ActionA = { // This is not allowed type: ACTION_A, // type: 'LITERAL_STRING_A' is allowed dataA: Ac
const ACTION_A = 'LITERAL_STRING_A';
const ACTION_B = 'LITERAL_STRING_B';
type ActionA = {
// This is not allowed
type: ACTION_A,
// type: 'LITERAL_STRING_A' is allowed
dataA: ActionAData,
}
type ActionB = {
// This is not allowed
type: ACTION_B,
// type: 'LITERAL_STRING_B' is allowed
dataB: ActionBData,
}
type Action = ActionA | ActionB;
function reducer(state: State, action: Action): State {
// Want to narrow Action to ActionA or ActionB based on type
switch (action.type) {
// case 'LITERAL_STRING_A': -- successfully narrow the type
case ACTION_A: // doesn't work
// action.dataA is accessible
...
}
...
}
不幸的是,您不能这样做,因为字符串不适合作为类型注释
如果有任何其他方法不强制在任何地方键入字符串文字,我很想知道
如果没有办法解决这个问题,也可以接受更高层次的建议,如何不需要为重复操作定义这些不相交的集合。我现在状态不佳,如果我看错了你的问题,请原谅。无论如何,我会尽力帮忙的。这就是你要找的吗
const actionTypes = {
FOO: 'FOO',
BAR: 'BAR'
}
type ActionType = $Keys<actionTypes> // one of FOO, BAR
function buzz(actionType: ActionType) {
switch(actionType) {
case actionTypes.FOO:
// blah
}
此外,如果您不需要单独的动作类型,您也可以这样做
type Action =
| {type: ACTION_A; dataA: ActionAData;}
| {type: ACTION_B; dataB: ActionBData;}
更好的方法是对常量值使用字符串文字类型:
我想把动作类型缩小到动作A或动作B类型。这样我就可以访问每个子类型的字段,而不必抱怨流。我在示例中看到使用文本字符串可以实现这一点,但我想知道是否可以使用enums@xvaldetaro啊,我明白了,谢谢你更新问题。真奇怪。通过常量进行细化似乎与通过字符串文本进行细化的效果相同。也许行动定义中的
type:typeof ACTION\u A
会起作用吗?
type Action =
| {type: ACTION_A; dataA: ActionAData;}
| {type: ACTION_B; dataB: ActionBData;}
const ACTION_A:'LITERAL_STRING_A' = 'LITERAL_STRING_A';
const ACTION_B:'LITERAL_STRING_B' = 'LITERAL_STRING_B';