由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
当前回答
因为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文档
其他回答
如果你想传递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有专门的函数或语法糖吗
TypeScript完全理解JavaScript版本== null。
通过这样的检查,TypeScript会正确地排除null和undefined。
More
https://basarat.gitbook.io/typescript/recap/null-undefined
晚加入这个线程,但我发现这个JavaScript黑客在检查一个值是否未定义非常方便
if(typeof(something) === 'undefined'){
// Yes this is undefined
}
我总是这样写:
var foo:string;
if(!foo){
foo="something";
}
这将会很好,我认为它是非常可读的。
如果你正在使用TypeScript,让编译器检查空值和未定义值(或可能存在的)是一个更好的方法,而不是在运行时检查它们。(如果您确实想在运行时检查,那么正如许多答案所表明的那样,只需使用value == null)。
使用编译选项strictNullChecks告诉编译器阻塞可能的空值或未定义值。如果你设置了这个选项,然后有一个你想要允许null和undefined的情况,你可以定义类型为type | null | undefined。