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

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


当前回答

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

其他回答

如果你想传递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中的运算符。 参见https://mariusschulz.com/blog/nullish-coalescing-the-operator-in-typescript

if( value ) {
}

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

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

Typescript包含javascript规则。

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

value == null ? "UNDEFINED" : value

这一行相当于:

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

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

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

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