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

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


当前回答

通常我做杂耍检查,芬顿已经说过了。 为了让它更具可读性,你可以使用ramda中的isNil。

import * as isNil from 'ramda/src/isNil';

totalAmount = isNil(totalAmount ) ? 0 : totalAmount ;

其他回答

一个更快更短的空检查符号可以是:

value == null ? "UNDEFINED" : value

这一行相当于:

if(value == null) {
       console.log("UNDEFINED")
} else {
    console.log(value)
}

特别是当你有很多空校验的时候它是一个很好的简短符号。

if(data){}

这是卑鄙的数据

零 未定义的 假 ....

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

if( value ) {
}

如果value不为true,则求值为true:

零 未定义的 南 空字符串" 0 假

Typescript包含javascript规则。

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