由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。

TypeScript有专门的函数或语法吗?


当前回答

最简单的方法是使用:

import {isNullOrUndefined} from 'util';

比:

如果isNullOrUndefined (foo (!)

其他回答

因为TypeScript是ES6 JavaScript的类型化超集。和lodash是一个javascript库。

使用lodash检查value是否为空或未定义可以使用_.isNil()来完成。

_.isNil(value)

参数

value(*):要检查的值。

返回

(boolean):如果值为空则返回true,否则返回false。

例子

_.isNil(null);
// => true

_.isNil(void 0);
// => true

_.isNil(NaN);
// => false

Link

Lodash文档

你可以用:

if (!!variable) {}

它等于写作

it (variable != null && variable != undefined) {}

你可以使用

if(x === undefined)

使用杂耍检查,你可以在一次命中测试null和undefined:

if (x == null) {

如果你使用严格检查,它只对设置为null的值为真,而对未定义的变量不为真:

if (x === null) {

你可以用这个例子尝试不同的值:

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未定义" "b == null" "b === null"

可能已经晚了!但是你可以用??typescript中的运算符。 参见https://mariusschulz.com/blog/nullish-coalescing-the-operator-in-typescript