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

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


当前回答

我们使用一个helper hasValue来检查null /undefined,并通过TypeScript确保不执行不必要的检查。(后者类似于TS如何抱怨if ("a" === undefined),因为它总是假的)。

始终使用这个始终是安全的,不像!val匹配空字符串,零等。它还避免了模糊==匹配的使用,这几乎总是一个坏的做法-没有必要引入异常。



type NullPart<T> = T & (null | undefined);

// Ensures unnecessary checks aren't performed - only a valid call if 
// value could be nullable *and* could be non-nullable
type MustBeAmbiguouslyNullable<T> = NullPart<T> extends never
  ? never
  : NonNullable<T> extends never
  ? never
  : T;

export function hasValue<T>(
  value: MustBeAmbiguouslyNullable<T>,
): value is NonNullable<MustBeAmbiguouslyNullable<T>> {
  return (value as unknown) !== undefined && (value as unknown) !== null;
}

export function hasValueFn<T, A>(
  value: MustBeAmbiguouslyNullable<T>,
  thenFn: (value: NonNullable<T>) => A,
): A | undefined {
  // Undefined matches .? syntax result
  return hasValue(value) ? thenFn(value) : 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();

奖金

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

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

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

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

你可以使用

if(x === undefined)