3

I am very confusing about TypeScript intersection, for example:

type A = 1 | 2;
type B = 2 | 3;

type AB = A & B;

type C = { a: 1, b: 2 };
type D = { b: 2, c: 3 };

type CD = C & D;

Type AB returns 2, this is easy to understand, but why CD returns {a: 1, b: 2, c: 3}, from my understanding, CD should returns {b: 2}, because a property only on C and c property only on D.

Simon MᶜKenzie
  • 8,344
  • 13
  • 50
  • 77
ChenLee
  • 1,371
  • 3
  • 15
  • 33
  • TS has a *structural* type system with structural *subtyping*. Every value of type `{a: 1, b: 2, c: 3}` is a value of type `C` (it has both required properties), as well as a value of type `D` (it has both required properties), and thus is a value of type `C & D`. (The fact that `c` is not present in `C` and `a` is not present in `D` doesn't matter here; you are allowed to add properties to an object type. If you couldn't, then subtyping via interface extension would break.) – jcalz Apr 15 '22 at 02:14
  • Similarly, every value of type `2` is a value of type `A` and a value of type `B`, and thus is a value of type `A & B`. Intersection has the same semantics in both cases: intersections of sets of values. See the answers to the linked questions for more info. – jcalz Apr 15 '22 at 02:14

0 Answers0