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

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


当前回答

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

其他回答

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

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

我们使用一个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;
}


if(data){}

这是卑鄙的数据

零 未定义的 假 ....

晚加入这个线程,但我发现这个JavaScript黑客在检查一个值是否未定义非常方便

 if(typeof(something) === 'undefined'){
   // Yes this is undefined
 }