由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
当前回答
你可以使用
if(x === undefined)
其他回答
我有这个问题,一些答案工作只是很好的JS,但不是TS这里的原因。
//JS
let couldBeNullOrUndefined;
if(couldBeNullOrUndefined == null) {
console.log('null OR undefined', couldBeNullOrUndefined);
} else {
console.log('Has some value', couldBeNullOrUndefined);
}
这很好,因为JS没有类型
//TS
let couldBeNullOrUndefined?: string | null; // THIS NEEDS TO BE TYPED AS undefined || null || Type(string)
if(couldBeNullOrUndefined === null) { // TS should always use strict-check
console.log('null OR undefined', couldBeNullOrUndefined);
} else {
console.log('Has some value', couldBeNullOrUndefined);
}
在TS中,如果变量未定义为null,当您试图检查该null时,tslint |编译器将报错。
//tslint.json
...
"triple-equals":[true],
...
let couldBeNullOrUndefined?: string; // to fix it add | null
Types of property 'couldBeNullOrUndefined' are incompatible.
Type 'string | null' is not assignable to type 'string | undefined'.
Type 'null' is not assignable to type 'string | undefined'.
可能已经晚了!但是你可以用??typescript中的运算符。 参见https://mariusschulz.com/blog/nullish-coalescing-the-operator-in-typescript
如果你正在使用TypeScript,让编译器检查空值和未定义值(或可能存在的)是一个更好的方法,而不是在运行时检查它们。(如果您确实想在运行时检查,那么正如许多答案所表明的那样,只需使用value == null)。
使用编译选项strictNullChecks告诉编译器阻塞可能的空值或未定义值。如果你设置了这个选项,然后有一个你想要允许null和undefined的情况,你可以定义类型为type | null | undefined。
最简单的方法是使用:
import {isNullOrUndefined} from 'util';
比:
如果isNullOrUndefined (foo (!)
晚加入这个线程,但我发现这个JavaScript黑客在检查一个值是否未定义非常方便
if(typeof(something) === 'undefined'){
// Yes this is undefined
}