typescripttypesoperator-precedenceunion-typesintersection-types

Intersection of union of different types is not what I expected


type T1 = 1 | 'b' & string | number // "b" | number
type T2 = 1 | 2 & 1 | 3 // 1 | 3

I'm new to TS. Can someone tell me why it's "b" | number and 1 | 3 and what's going on here?


Solution

  • & has higher precedence than |

    Thus your code is interpreted as:

    type T1 = 1 | ('b' & string) | number 
    type T2 = 1 | (2 & 1) | 3
    

    in which case "b" | number and 1 | 3 make sense.

    If you add parenthesis it will work the way you have in mind:

    type T1 = (1 | 'b') & (string | number) // 1 | "b"
    type T2 = (1 | 2) & (1 | 3) // 1