sevcsik - 5 months ago 27

TypeScript Question

I can't understand the logic behind the terms *union types* and *intersection types* in TypeScript.

Pragmatically, if the properties of different types are sets of properties, if I combine them with the

`&`

`|`

Wikipedia seems to back that logic:

The power set (set of all subsets) of any given nonempty set S forms a Boolean algebra, an algebra of sets, with the two operations ∨ := ∪ (union) and ∧ := ∩ (intersection).

However, according to typescriptlang.org, it's exactly the oppopsite:

`&`

`|`

I'm sure there is another way of looking at it, but I cannot figure it out.

Answer

The type `A | B`

refers to objects which are **either** `A`

or `B`

. In other words, values of such type are drawn from the **union** of values for `A`

and values for `B`

.

The type `A & B`

refers to objects which are **both** `A`

and `B`

. In other words, values of such type are drawn from the **intersection** of values for `A`

and values for `B`

.

The naming and semantics are identical in other languages such as C++.