Typescript 2.0 typeof null 变量未定义 [英] Typescript 2.0 typeof null variable is undefined

查看:56
本文介绍了Typescript 2.0 typeof null 变量未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习 Typescript,我遇到了一个奇怪的行为,我试图声明两个变量,一个 null 和另一个 undefined 因为它是引入的新功能在打字稿 2.0 中.

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);

我期待看到这个输出:

null
undefined

但它是:

undefined
undefined

更多,当我这样做时:

if(typeof myNullVar === 'null'){
    console.log('null');
}
else if (typeof myNullVar === 'undefined'){
    console.log('undefined');
}

我得到 undefined

null 和 Typescript 中的 undefined 是一回事吗?如果是,两者兼有的目的是什么?

Is null the same thing as undefined in Typescript? if yes, what is the purpose of having both?

推荐答案

类型注解不影响运行时行为,typeof 是一种运行时构造.

Type annotations don't affect runtime behavior and typeof is a runtime construct.

未初始化变量的值是undefinedtypeof undefined总是"undefined".请注意,这是一个 string,与 undefined 本身的值不同.

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.

既然要上来了,typeof null就是"object".

这篇关于Typescript 2.0 typeof null 变量未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆