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

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


当前回答

一个更快更短的空检查符号可以是:

value == null ? "UNDEFINED" : value

这一行相当于:

if(value == null) {
       console.log("UNDEFINED")
} else {
    console.log(value)
}

特别是当你有很多空校验的时候它是一个很好的简短符号。

其他回答

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

你可以使用

if(x === undefined)

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

TypeScript完全理解JavaScript版本== null。

通过这样的检查,TypeScript会正确地排除null和undefined。

More

https://basarat.gitbook.io/typescript/recap/null-undefined

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

奖金

通常我做杂耍检查,芬顿已经说过了。 为了让它更具可读性,你可以使用ramda中的isNil。

import * as isNil from 'ramda/src/isNil';

totalAmount = isNil(totalAmount ) ? 0 : totalAmount ;