From the TypeScript spec:
The Null type is a subtype of all types, except the Undefined type. The undefined type is a subtype of all types.
From this, I believe, we can conclude that undefined
is a subtype of null
and, for example, of number
. We can not assign supertype to the subtype, for instance, number
is not assignable to the undefined
. Why null
, while being a supertype to undefined
is assignable to the undefined
?
let x: undefined;
x = 5; // Error
let y: undefined;
y = null; // OK
Because of the way many algorithms in the original TypeScript spec were defined, it was very desirable for the subtype relationship to be strictly directional (e.g. no non-identical S
and T
existed such that S
was a subtype of T
and T
was a subtype of S
, minus any
which was always allowed to do weird things). Had this not been the case, you would have seen some weird-ish behavior, mostly around the types of array literals depending on the order of their elements.
There are some other subtle problems which would be introduced if the subtype relationship allowed circularity, none of which I can specifically recall at the moment. The introduction of union types effectively eliminated the "best common type" algorithm which relied heavily upon noncircular subtyping, so these theoretical problems are probably not noticeable in current versions of TypeScript.
The exact choice of which to make a subtype of the other is pretty much arbitrary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With