如何避免使用文字字符串来缩小流中不相交的联合

xva*_*aro 5 flowtype redux

我在网上找到的用于缩小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: 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
      ...
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

遗憾的是,您不能这样做,因为字符串不符合类型注释.

如果还有其他任何方法可以在任何地方强制输入字符串文字,我很乐意知道.

如果没有解决方法,也接受更高级别的建议如何不需要为redux操作定义这些不相交的集合.

Nik*_*ita 0

我现在状态不佳,如果我读错了你的问题,我很抱歉。无论如何我都会尽力提供帮助。这是您要找的吗?

const actionTypes = {
  FOO: 'FOO',
  BAR: 'BAR'
}

type ActionType = $Keys<actionTypes> // one of FOO, BAR

function buzz(actionType: ActionType) {
  switch(actionType) {
    case actionTypes.FOO:
      // blah
  }
Run Code Online (Sandbox Code Playgroud)

这应该有效。抱歉,如果我的语法有点不对劲。

如果您问如何避免列出所有操作类型,那么type Action = ActionA | ActionB抱歉,我不知道,我认为这就是您这样做的方式。如果我没记错的话,Flow 最近引入了一种稍微好一点的定义长联合的语法:

type Action =
  | ActionA
  | ActionB
  | ActionC
Run Code Online (Sandbox Code Playgroud)

另外,如果您不需要单独的操作类型,您可以这样做

type Action =
  | {type: ACTION_A; dataA: ActionAData;}
  | {type: ACTION_B; dataB: ActionBData;}
Run Code Online (Sandbox Code Playgroud)