I am a bit confused about the name Intersection Types in Typescript.
In set theory, intersection would imply that only properties that are common to both types would be available in the intersection of the two.
In fact, that is how Typescript behaves if I create an intersection between primitives.
type A = string | number
type B = number | boolean
type C = A & B
type D = string
type E = number
type F = D & B
In this case, TS infers C
to be number
, and F
to be never
.
However, when it comes to objects, creating an intersection creates a new type/interface that combines the properties of the used types -
From the documentation
TypeScript provides another construct called intersection types that is mainly used to combine existing object types
The behavior for objects makes perfect sense when you look at this way. And using &
also makes sense.
So, my questions are these:
Maybe it is somehow related to this explanation with Union types ?
An intersection between two sets would yield elements that are in both sets.
Types are just descriptions of sets of values.
So for the intersection of primitives string & number
, what value is in both the string
set and the number
set, ie. can be both a string
and number
at the same time. The answer is there is no such value. So we get never
(the empty set)
For object types the result is a bit different. Object types describe sets where the value must have at least the properties described by the type. So values in the set { name: string, onlyA: string[] }
could have a property onlyB
, but they are not required to have it (ex).
Going back to the intersection ObA & ObB
, values in this intersection must satisfy both the description of ObA
and ObB
. So the values in this set will be the values from ObA
that also have an onlyB
property, and the values from ObB
that also have an onlyA
property. Basically values that satisfy both set descriptions, which for object types unlike for primitives we can construct by creating objects with properties from both types.
My tsconf workshop starts with a "Types as sets" section you might find interesting.