Typescript 2.0 typeof null variable is undefined

僤鯓⒐⒋嵵緔 提交于 2020-01-03 22:28:56

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/49947334/typescript-2-0-typeof-null-variable-is-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!