Home > Back-end >  Intersection of union of different types is not what I expected
Intersection of union of different types is not what I expected

Time:01-16

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?

CodePudding user response:

& 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
  • Related