Union A|B of types + overlapping member of different type. Conflict resolution logic

Viewed 44

We have:

// 1 case - conflict number VS boolean

type A2 = {
  x: number;
  y: number;
};

type B2 = {
  y: boolean; // conflict
  z: number;
};

type U2 = A2 | B2;

let u2: U2;

u2 = { x: 1, y: 1 };
u2 = { y: false, z: 5 };

u2 = { x: 1, y: false, z: 3 }; // error
u2 = { x: 1, y: 2, z: 3 }; // error

// 2 case - conflict number VS string

type A = {
  x: number;
  y: number;
};

type B = {
  y: string; // conflict
  z: number;
};

type U = A | B;

let u: U;

u = { x: 1, y: 2 };
u = { y: "2", z: 3 };

u = { x: 1, y: 2, z: 3 }; // ok. why?
u = { x: 1, y: "2", z: 3 }; // ok. why?

i'm ok with error logic in case #1 - union of types U2 makes values possess properties of type A2 or of type B2, or of both (but in our concrete case we have type conflict for y, so "both" is not working here, we can't have y in value at all).

Question: why case #2 is ok? why it does not follow the same logic and y is not being excluded, what am i missing here? is there any document, PR that describes this case 1 vs 2 difference? I'm using TS 4.7. thanks.

0 Answers
Related