由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
当前回答
if( value ) {
}
如果value不为true,则求值为true:
零 未定义的 南 空字符串" 0 假
Typescript包含javascript规则。
其他回答
一个更快更短的空检查符号可以是:
value == null ? "UNDEFINED" : value
这一行相当于:
if(value == null) {
console.log("UNDEFINED")
} else {
console.log(value)
}
特别是当你有很多空校验的时候它是一个很好的简短符号。
我有这个问题,一些答案工作只是很好的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是ES6 JavaScript的类型化超集。和lodash是一个javascript库。
使用lodash检查value是否为空或未定义可以使用_.isNil()来完成。
_.isNil(value)
参数
value(*):要检查的值。
返回
(boolean):如果值为空则返回true,否则返回false。
例子
_.isNil(null);
// => true
_.isNil(void 0);
// => true
_.isNil(NaN);
// => false
Link
Lodash文档
如果你正在使用TypeScript,让编译器检查空值和未定义值(或可能存在的)是一个更好的方法,而不是在运行时检查它们。(如果您确实想在运行时检查,那么正如许多答案所表明的那样,只需使用value == null)。
使用编译选项strictNullChecks告诉编译器阻塞可能的空值或未定义值。如果你设置了这个选项,然后有一个你想要允许null和undefined的情况,你可以定义类型为type | null | undefined。
我认为这个答案需要更新,检查编辑历史的旧答案。
基本上,您有三种不同的情况- 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。