I am newly learning Typescript and I run through a strange behavior, I was trying to declare two variables one null and the other undefined as it is a new feature introduced in Typescript 2.0.
let myNullVar :null;
let myNullVar2 : undefined;
console.log(typeof myNullVar);
console.log(typeof myNullVar2);
I was expecting to see this output:
null
undefined
But it was:
undefined
undefined
More, when I do this:
if(typeof myNullVar === 'null'){
console.log('null');
}
else if (typeof myNullVar === 'undefined'){
console.log('undefined');
}
I get undefined
Is null the same thing as undefined in Typescript? if yes, what is the purpose of having both?
Type annotations don't affect runtime behavior and typeof is a runtime construct.
The value of an uninitialized variable is undefined, and typeof undefined is always "undefined". Note that this is a string, not the same as the value undefined itself.
Since it's about to come up, typeof null is "object".
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