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

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


当前回答

在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();

奖金

其他回答

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

基本上,您有三种不同的情况- 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。

对于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
  }
}

使用杂耍检查,你可以在一次命中测试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"

All,

得票最多的答案,如果你在研究一个对象,就不适用了。在这种情况下,如果属性不存在,检查将不起作用。这就是我们案例中的问题:请看这个例子:

var x =
{ name: "Homer", LastName: "Simpson" };

var y =
{ name: "Marge"} ;

var z =
{ name: "Bart" , LastName: undefined} ;

var a =
{ name: "Lisa" , LastName: ""} ;

var hasLastNameX = x.LastName != null;
var hasLastNameY = y.LastName != null;
var hasLastNameZ = z.LastName != null;
var hasLastNameA = a.LastName != null;



alert (hasLastNameX + ' ' + hasLastNameY + ' ' + hasLastNameZ + ' ' + hasLastNameA);

var hasLastNameXX = x.LastName !== null;
var hasLastNameYY = y.LastName !== null;
var hasLastNameZZ = z.LastName !== null;
var hasLastNameAA = a.LastName !== null;

alert (hasLastNameXX + ' ' + hasLastNameYY + ' ' + hasLastNameZZ + ' ' + hasLastNameAA);

结果:

true , false, false , true (in case of !=)
true , true, true, true (in case of !==) => so in this sample not the correct answer

plunkr链接:https://plnkr.co/edit/BJpVHD95FhKlpHp1skUE

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

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

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