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

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


当前回答

如果你正在使用TypeScript,让编译器检查空值和未定义值(或可能存在的)是一个更好的方法,而不是在运行时检查它们。(如果您确实想在运行时检查,那么正如许多答案所表明的那样,只需使用value == null)。

使用编译选项strictNullChecks告诉编译器阻塞可能的空值或未定义值。如果你设置了这个选项,然后有一个你想要允许null和undefined的情况,你可以定义类型为type | null | undefined。

其他回答

您可以使用三元运算符和新的空合并运算符轻松做到这一点。

首先:使用三元来检查它是否为真。如果是,则返回false,因此If语句不会运行。

第二:因为现在知道值是假的,所以如果值为空,可以使用空合并运算符返回true。由于它将为任何其他值返回自身,如果它不为null,则将使if语句正确失败。

let x = true; console.log("starting tests") if (x?false:x ?? true){ console.log(x,"is nullish") } x = false if (x?false:x ?? true){ console.log(x,"is nullish") } x = 0; if (x?false:x ?? true){ console.log(x,"is nullish") } x=1; if (x?false:x ?? true){ console.log(x,"is nullish") } x=""; if (x?false:x ?? true){ console.log(x,"is nullish") } x="hello world"; if (x?false:x ?? true){ console.log(x,"is nullish") } x=null; if (x?false:x ?? true){ console.log(x,"is nullish") } x=undefined; if (x?false:x ?? true){ console.log(x,"is nullish") }

最简单的方法是使用:

import {isNullOrUndefined} from 'util';

比:

如果isNullOrUndefined (foo (!)

我总是这样写:

var foo:string;

if(!foo){
   foo="something";    
}

这将会很好,我认为它是非常可读的。

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

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

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

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