I
I
ivan05122020-03-23 20:28:17
typescript
ivan0512, 2020-03-23 20:28:17

What is the logic of intersection and union types?

As I understand it, after reading about these types, they should be treated as if they were sets. That is | | can merge two sets, and & finds their intersection. This example confirms this logic. Using an enum, the string type is discarded

type A = number | string;
type B = A & number; // number


However, I have a question when considering the second case. If we take objects instead of primitive types. Here & no longer finds an intersection ({ a: number }), but combines two objects. Which seems like a mistake to me. I know I'm wrong somewhere, but I can't figure out where.
type C = { a: number } | { b: number };
type D = C & { a: number };

const test2: D = {
  a: 1,
  b: 2
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan Lopatin, 2020-03-24
@ivan0512

You misunderstood. Just read | as "or" and & as "and".
number | string means that the variable contains either a number or a string.
number &string means that the variable will be both a number and a string at the same time. And it does not matter how it is implemented, and whether it is feasible in principle (no).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question