Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript 2.0 typeof null variable is undefined

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?

like image 214
achref Avatar asked Nov 23 '25 06:11

achref


1 Answers

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".

like image 149
Ryan Cavanaugh Avatar answered Nov 27 '25 14:11

Ryan Cavanaugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!