Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In TypeScript why is it OK to assign `null` to the variable of type `undefined` and vice versa

Tags:

typescript

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
like image 606
Oleksandr Nechai Avatar asked Oct 29 '22 12:10

Oleksandr Nechai


1 Answers

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.

like image 166
Ryan Cavanaugh Avatar answered Nov 12 '22 16:11

Ryan Cavanaugh