In Typescript'e there are two great features (there are certainly not two of them, but I would like to highlight exactly two specific ones). Here is a link to of the documentation. There is a type of intersection ( Intersection Types ) and a type of union ( Union Types ), and they work like this:

1) Intersection ( Intersection Types ) - let's say there is a variable lsp and in the code it is declared like this:

let psl : Person & Serializable & Loggable ,

here lsp typed and includes all elements of the types Person , Serializable and Loggable at the same time. This means that an object of this type will have all the elements of all three types, which can be graphically represented as:

enter image description here

2) Union Types — A union type describes a value that can be one of several types and is declared in code like this:

 function getSmallPet(): Fish | Bird { // ... } 

It differs from the type of intersection in that if we have a value of this type, we can access only those elements that are common to all types in the union.

My question is that I do not understand why these entities are so named? An intersection, for example, in set theory, on the contrary, includes only elements common to all, and not as in a type script, and with Union, the same story is exactly the opposite.

  • @VasyaMilovidov, also take into account that the full name of the second construction is a discriminated union , a discriminatory union (not a union, Microsoft decided this way from the F # language), that is, an unequal union, where some set may prevail over the other - overthesanity

1 answer 1

You can look at it from the other side.

Consider 4 sets: red things, blue things, big things and small things.

If we cross (intersect) the sets of all red things and all small things, we end up with a union of properties - everything in the set will be both red and small.

But if we take the union of the red small and blue small , then as a result only the size property will be common, therefore only the small will enter the intersecting of the "red small" and "blue small".

In other words, when we combine a region of value, we get the intersection of property sets and vice versa.

translation of the answer @RyanCavanaugh