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:
- Why does the behavior seem different for objects and primitives?
- Why was the name intersection chosen ?
Maybe it is somehow related to this explanation with Union types ?