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

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


当前回答

最简单的方法是使用:

import {isNullOrUndefined} from 'util';

比:

如果isNullOrUndefined (foo (!)

其他回答

如果你使用本地存储,小心,你可能会以字符串undefined而不是值undefined结束:

localStorage.setItem('mykey',JSON.stringify(undefined));
localStorage.getItem('mykey') === "undefined"
true

人们可能会发现这个很有用:https://github.com/angular/components/blob/master/src/cdk/coercion/boolean-property.spec.ts

/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

/** Coerces a data-bound value (typically a string) to a boolean. */
export function coerceBooleanProperty(value: any): boolean {
  return value != null && `${value}` !== 'false';
}

import {coerceBooleanProperty} from './boolean-property';

describe('coerceBooleanProperty', () => {

  it('should coerce undefined to false', () => {
    expect(coerceBooleanProperty(undefined)).toBe(false);
  });

  it('should coerce null to false', () => {
    expect(coerceBooleanProperty(null)).toBe(false);
  });

  it('should coerce the empty string to true', () => {
    expect(coerceBooleanProperty('')).toBe(true);
  });

  it('should coerce zero to true', () => {
    expect(coerceBooleanProperty(0)).toBe(true);
  });

  it('should coerce the string "false" to false', () => {
    expect(coerceBooleanProperty('false')).toBe(false);
  });

  it('should coerce the boolean false to false', () => {
    expect(coerceBooleanProperty(false)).toBe(false);
  });

  it('should coerce the boolean true to true', () => {
    expect(coerceBooleanProperty(true)).toBe(true);
  });

  it('should coerce the string "true" to true', () => {
    expect(coerceBooleanProperty('true')).toBe(true);
  });

  it('should coerce an arbitrary string to true', () => {
    expect(coerceBooleanProperty('pink')).toBe(true);
  });

  it('should coerce an object to true', () => {
    expect(coerceBooleanProperty({})).toBe(true);
  });

  it('should coerce an array to true', () => {
    expect(coerceBooleanProperty([])).toBe(true);
  });
});

我们使用一个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操场上做了不同的测试:

http://www.typescriptlang.org/play/

let a;
let b = null;
let c = "";
var output = "";

if (a == null) output += "a is null or undefined\n";
if (b == null) output += "b is null or undefined\n";
if (c == null) output += "c is null or undefined\n";
if (a != null) output += "a is defined\n";
if (b != null) output += "b is defined\n";
if (c != null) output += "c is defined\n";
if (a) output += "a is defined (2nd method)\n";
if (b) output += "b is defined (2nd method)\n";
if (c) output += "c is defined (2nd method)\n";

console.log(output);

给:

a is null or undefined
b is null or undefined
c is defined

so:

检查(a == null)是否正确,以知道a是否为空或未定义 检查(a != null)是否正确,以知道是否定义了a 检查(a)是否错误,以知道a是否被定义

最简单的方法是使用:

import {isNullOrUndefined} from 'util';

比:

如果isNullOrUndefined (foo (!)

你可以使用

if(x === undefined)