Intersection of primitives
type foo = number;
type bar = boolean;
type baz = foo & bar;
There's no intersection with foo and bar.
Thus baz
type is never
Great, that makes sense.
Intersection of Objects
type foo = {
fizz: number
};
type bar = {
fuzz: boolean
};
type baz = foo & bar;
There are no properties in foo
or bar
that intersect.
Just like in the primitive intersection example.
But instead of being a never
type, the type enforces objects of type baz
to have the combination of all properties of baz
and bar
.
For example:
type foo = {
fizz: number
};
type bar = {
fuzz: boolean
};
type baz = foo & bar;
// FAILS
const o: baz = {
fuzz: true
}
// FAILS
const o: baz = {
fizz: 1,
}
// PASSES
const o: baz = {
fizz: 1,
fuzz: true
}
To recap: The intersection of foo and bar in the primitive example has nothing. Thus, it's type was never.
The intersection of foo and bar in the object example has nothing. Yet, it's type is more of a union than an intersection. i.e. Objects of type baz
require properties of both foo
and bar
.
Question
In the primitive example, it behaves like an intersection. Yet in the object example, it behaves not like an intersection. Why are these behaviors inconsistent?
Why does the intersection of objects behave like a union, and yet the intersection of primitives behave like a proper intersection?