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

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


当前回答

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

首先:使用三元来检查它是否为真。如果是,则返回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") }

其他回答

在TypeScript 3.7中,我们现在有可选的链接和Nullish Coalescing来同时检查null和undefined,例如:

let x = foo?.bar.baz();

这段代码将检查foo是否有定义,否则它将返回undefined

旧方法:

if(foo != null && foo != undefined) {
   x = foo.bar.baz();
} 

这样的:

let x = (foo === null || foo === undefined) ? undefined : foo.bar();

if (foo && foo.bar && foo.bar.baz) { // ... }

与可选的链接将:

let x = foo?.bar();

if (foo?.bar?.baz) { // ... }

另一个新特性是Nullish Coalescing,例如:

let x = foo ?? bar(); // return foo if it's not null or undefined otherwise calculate bar

老方法:

let x = (foo !== null && foo !== undefined) ?
foo :
bar();

奖金

因为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(x === undefined)

对于Typescript 2.x。X你应该用以下方式(使用类型保护):

博士tl;

function isDefined<T>(value: T | undefined | null): value is T {
  return <T>value !== undefined && <T>value !== null;
}

Why?

这样,isDefined()将尊重变量的类型,下面的代码将知道这个检入帐户。

例1 -基本检查:

function getFoo(foo: string): void { 
  //
}

function getBar(bar: string| undefined) {   
  getFoo(bar); //ERROR: "bar" can be undefined
  if (isDefined(bar)) {
    getFoo(bar); // Ok now, typescript knows that "bar' is defined
  }
}

例2 -类型尊重:

function getFoo(foo: string): void { 
  //
}

function getBar(bar: number | undefined) {
  getFoo(bar); // ERROR: "number | undefined" is not assignable to "string"
  if (isDefined(bar)) {
    getFoo(bar); // ERROR: "number" is not assignable to "string", but it's ok - we know it's number
  }
}

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

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

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