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

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


当前回答

最简单的方法是使用:

import {isNullOrUndefined} from 'util';

比:

如果isNullOrUndefined (foo (!)

其他回答

我认为这个答案需要更新,检查编辑历史的旧答案。

基本上,您有三种不同的情况- null、undefined和未声明,请参阅下面的代码片段。

// bad-file.ts
console.log(message)

你会得到一个错误,说变量消息是未定义的(也就是未声明的),当然,Typescript编译器不应该让你这样做,但真的没有什么可以阻止你。

// evil-file.ts
// @ts-gnore
console.log(message)

编译器很乐意只编译上面的代码。 如果你确定所有变量都声明了,你就可以这么做

if ( message != null ) {
    // do something with the message
}

上面的代码将检查null和未定义,但是如果消息变量可能未声明(为了安全),您可以考虑以下代码

if ( typeof(message) !== 'undefined' && message !== null ) {
    // message variable is more than safe to be used.
}

注意:这里的顺序typeof(message) !== 'undefined' && message !== null非常重要,你必须先检查未定义状态,否则它将与message != null相同,谢谢@Jaider。

你可以使用

if(x === undefined)

晚加入这个线程,但我发现这个JavaScript黑客在检查一个值是否未定义非常方便

 if(typeof(something) === 'undefined'){
   // Yes this is undefined
 }

试试这个,用!!运算符和变量。

let check;
if (!!check) {
  console.log('check is not null or not undefined');
} else {
  console.log('check is  null or  undefined');
}

它在Angular中非常有用。 检查任何变量的undefined和null。

你可以用:

if (!!variable) {}

它等于写作

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