问题
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