Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does single & and single | operators do in flow js?

There is a piece of code in one of the files in react-native repo here as shown below:

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});

What are the single & and | operators supposed to do here?

I am getting an Unexpected token error in this file at the first | operator when I am running a jest test case on my react-native app. I am running node version 5.9.1. My other team mate who is running node version 8.x doesn't run into the unexpected token error. So, I am assuming these operators are introduced post node version 5.9.1. Is that correct?

like image 803
Varun Gupta Avatar asked Dec 23 '22 15:12

Varun Gupta


1 Answers

In this case, these are for Flow types. They represent Union Types and Intersection Types. Flow annotations give you static type checking for your code, and here they define the structure that an object must have to be considered a valid Operation type by Flow, such as when passing an object to a function that expects an Operation argument of this form. They are not an official part of the JS language. To use them, you need to enable flow annotations in babel or use flow-remove-types:

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

However, the & and | operators do exist in JavaScript, but for bitwise arithmetic.

like image 53
sbking Avatar answered Dec 28 '22 11:12

sbking