由于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有专门的函数或语法糖吗

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

奖金

如果你想传递tslint而不设置严格布尔表达式为allow-null-union或allow-undefined-union,你需要从节点的util模块中使用isNullOrUndefined或滚动你自己的:

// tslint:disable:no-null-keyword
export const isNullOrUndefined =
  <T>(obj: T | null | undefined): obj is null | undefined => {
    return typeof obj === "undefined" || obj === null;
  };
// tslint:enable:no-null-keyword

不完全是语法糖,但当你的tslint规则很严格时很有用。

简单的答案

虽然Typescript是一种强类型语言,但它在继承自Javascript的指针和变量初始化方面也存在同样的问题。 Javascript不检查变量在上下文中是否存在,这是很常见的未定义状态。

如果值为null,undefined,0,false,"",NaN:

if ( value )
or
if ( !!value )

对于否定条件句:

if ( !value )

测试是否为空或未定义:

if ( value == null )

只测试null:

if ( value === null )

只测试undefined:

if ( value === undefined )

更详细的回答

1-如果value不是:null, undefined, NaN,空字符串",0,false,它将计算为true 如果值为null、undefined、NaN、空字符串、0或false,将转到else条件。

if ( value ) {
  console.log('value is something different from 0, "", false, NaN, null, undefined');
} else {
  console.log('value is 0, "", false, NaN, null or undefined');
}
if ( !!value ) {
  console.log('value is something different from 0, "", false, NaN, null, undefined');
} else {
  console.log('value is 0, "", false, NaN, null or undefined');
}

2-如果你想要一个否定的条件,那么你需要使用:

if ( !value ) {
  console.log('value is 0, "", false, NaN, null or undefined');
} else {
  console.log('value is something different from 0, "", false, NaN, null, undefined');
}

3-如果value为空或未定义,它将计算

if ( value == null ) {
  console.log('is null or undefined');
} else {
  console.log('it isnt null neither undefined');
}

4-使用布尔条件不工作。 如果值为null, undefined, 0,空字符串,NaN,它将不会计算为true或false 这两个条件都会转到else条件。 如果value是布尔变量,则例外。

if ( value==true ) {
} else { 
}
if ( value==false ) {
} else { 
}

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

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