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

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


当前回答

简单的答案

虽然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
 }

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

如果你使用本地存储,小心,你可能会以字符串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);
  });
});

我在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是否被定义

我总是这样写:

var foo:string;

if(!foo){
   foo="something";    
}

这将会很好,我认为它是非常可读的。