The explanation seems adequate.
Another method to express "X
is a subtype of Y
" is by stating that "X
is assignable to Y
". Therefore, you could reword the definition as follows:
If A is a subtype of X or B is a subtype of X, then A & B is a subtype of X.
For instance, if you have a value of type Cat & Warm
, it can be stored in a variable of type Cat
, Warm
, and even Animal
due to the fact that Cat
is a subtype of Animal
. In essence, Cat & Warm
is a subtype of Cat
, Warm
, and Animal
.
In the given scenario, A {x:1} and B {y:1} are not assignable to X {x:1;y:1}, but I is assignable to X.
Indeed, A
cannot be assigned to A & B
, and similarly, B
cannot be assigned to A & B
. The clarification implies that A & B
can be assigned to A
and also to B
.
When stated that "X
is assignable to Y
", it signifies that having a variable x
of type X
is permissible:
const y: Y = x
Hence, the following code segments are acceptable:
const a: A = a_and_b
const b: B = a_and_b
However, these expressions are invalid:
const ab: A & B = a
const ab: A & B = b
Example (playground link):
type A = {x: 1} | {z: 42}
type B = {x: 1}
type C = {y: 2}
function f(bc: B & C) {
const b: B = bc // Acceptable because B & C can be assigned to B
const c: C = bc // Acceptable because B & C can be assigned to C
const a: A = bc // Valid since B is assignable to A, thus B & C is assignable to A
}
function g(b: B) {
const bc: B & C = b // Not valid, does not work the other way around
}
In your specific case, when invoking the functions f
with a
and b
, you're essentially replicating what's happening in the function g
. This will generate an error because A
cannot be assigned to A & B
, and likewise, B
cannot be assigned to A & B
.