【问题标题】:Flowtype enum actions reduxFlowtype 枚举动作 redux
【发布时间】:2018-05-24 17:10:50
【问题描述】:

仍然很难在我的 react/redux 应用程序中使用 Flow 来检查所有内容。

输入我的操作时,我得到:

type MessageSentAction = { type: 'MSG_SENT', 
  message: string,  
}
type Action = MessageSentAction | AnotherAction;

对此没有任何问题,但我想将类型 MSG_SENT 替换为常量。

const actionTypes = { MESSAGE_SENT = 'MSG_SENT'}
...
type MessageSentAction = { type: ActionTypes.MESSAGE_SENT, 
  message: string,  
}

我怎样才能让它工作?我不希望动作字符串在动作、reducer 和类型中重复...... 上面的示例给出了一个错误:“Ineligible value used in/as flow type annotation.”

【问题讨论】:

    标签: reactjs redux flowtype


    【解决方案1】:

    你可以使用typeof操作符

    const actionTypes = { MESSAGE_SENT: 'MSG_SENT'}
    
    type MessageSentAction = { 
      type: typeof actionTypes.MESSAGE_SENT, 
      message: string,  
    }
    

    【讨论】:

    • 不完全一样...当将所有类型定义为 type: 'MSG_SENT' 时,分配另一个值而不是给定类型时会出错。当使用 typeof ...我也可以将 type 定义为 type: string
    • 好的,这个问题并不清楚。但我看到你已经找到了解决方案,干杯
    【解决方案2】:

    刚刚找到...供参考:

    const ACTION_TYPES = { MESSAGE_SENT: 'MSG_SENT', TEST: 'test'};
    type ActionType = $Values<typeof ACTION_TYPES>;
    
    type MessageSentAction = { type: ActionType, 
      message: string,  
    }
    
    function test(t: MessageSentAction) {
      t.type = 'MSG_SENT';
    }
    

    当将 t.type 更改为 ACTION_TYPES 值之外的内容时,我会得到一个流错误。

    这与之前的答案不同,任何给定的字符串都可以

    【讨论】:

      猜你喜欢
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      相关资源
      最近更新 更多