【问题标题】:What does single & and single | operators do in flow js?单&单是什么意思?运营商在流js中做什么?
【发布时间】:2018-01-11 09:25:24
【问题描述】:

react-nativerepohere的其中一个文件中有一段代码如下图:

export type Operation =
  & {instanceID: DebugID}
  & (
    | {type: 'mount', payload: string}
    | {type: 'insert child', payload: {toIndex: number, content: string}}
    | {type: 'move child', payload: {fromIndex: number, toIndex: number}}
    | {type: 'replace children', payload: string}
    | {type: 'replace text', payload: string}
    | {type: 'replace with', payload: string}
    | {type: 'update styles', payload: mixed /* Style Object */}
    | {type: 'update attribute', payload: {[name: string]: string}}
    | {type: 'remove attribute', payload: string});

单个 &| 运算符在这里应该做什么?

当我在我的 react-native 应用程序上运行 jest 测试用例时,我在第一个 | 运算符处的此文件中收到 Unexpected token 错误。我正在运行节点版本5.9.1。我的另一个运行节点版本8.x 的队友没有遇到意外的令牌错误。所以,我假设这些运算符是在节点版本5.9.1 之后引入的。对吗?

【问题讨论】:

  • 附带说明,我强烈建议您和您的整个团队至少使用相同版本的节点!在具有不同软件版本的各种不同环境中测试您的代码并不是一个好主意,因为您往往会遇到很多“好吧,它可以在我的机器上运行!”的情况。更好的解决方案是使用 Vagrant 之类的工具来自动配置开发环境,这些环境使用与您的生产环境相同的软件版本。
  • 对于问题中的混淆,我深表歉意。我知道按位 &| 运算符,但我以前从未见过这样使用它们,很明显它们在上面的代码中没有用作按位运算符。 @sbking 是正确的,它们是 flow 类型。

标签: javascript node.js react-native jestjs


【解决方案1】:

在这种情况下,这些用于流类型。它们代表Union TypesIntersection Types。 Flow annotations 为您的代码提供静态类型检查,在这里它们定义了 Flow 必须将对象视为有效的 Operation 类型的结构,例如将对象传递给需要 Operation 参数的函数时这种形式的。它们不是 JS 语言的官方部分。要使用它们,您需要在 babel 中启用流注解或使用flow-remove-types

https://flow.org/en/docs/install/

但是,&| 运算符确实存在于 JavaScript 中,但用于 bitwise arithmetic

【讨论】:

    猜你喜欢
    • 2017-07-14
    • 2010-10-24
    • 1970-01-01
    • 2023-03-04
    • 2011-11-19
    • 2011-09-05
    • 2011-12-11
    相关资源
    最近更新 更多