有没有办法同时检查“null"和“undefined"? [英] Is there a way to check for both `null` and `undefined`?

查看:25
本文介绍了有没有办法同时检查“null"和“undefined"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为 TypeScript 是强类型的,所以简单地使用 if () {} 来检查 nullundefined 听起来不对.

Since TypeScript is strongly-typed, simply using if () {} to check for null and undefined doesn't sound right.

TypeScript 是否有专门的函数或语法糖?

Does TypeScript have any dedicated function or syntax sugar for this?

推荐答案

使用杂耍检查,您可以一次测试nullundefined:

Using a juggling-check, you can test both null and undefined in one hit:

if (x == null) {

如果您使用严格检查,它只会对设置为 null 的值为真,对于未定义的变量不会评估为真:

If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:

if (x === null) {

您可以使用以下示例尝试使用各种值:

You can try this with various values using this example:

var a: number;
var b: number = null;

function check(x, name) {
    if (x == null) {
        console.log(name + ' == null');
    }

    if (x === null) {
        console.log(name + ' === null');
    }

    if (typeof x === 'undefined') {
        console.log(name + ' is undefined');
    }
}

check(a, 'a');
check(b, 'b');

输出

"a == null"

"a == null"

a 未定义"

"b == null"

"b == null"

"b === null"

"b === null"

这篇关于有没有办法同时检查“null"和“undefined"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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