由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
当前回答
晚加入这个线程,但我发现这个JavaScript黑客在检查一个值是否未定义非常方便
if(typeof(something) === 'undefined'){
// Yes this is undefined
}
其他回答
在TypeScript 3.7中,我们现在有可选的链接和Nullish Coalescing来同时检查null和undefined,例如:
let x = foo?.bar.baz();
这段代码将检查foo是否有定义,否则它将返回undefined
旧方法:
if(foo != null && foo != undefined) {
x = foo.bar.baz();
}
这样的:
let x = (foo === null || foo === undefined) ? undefined : foo.bar();
if (foo && foo.bar && foo.bar.baz) { // ... }
与可选的链接将:
let x = foo?.bar();
if (foo?.bar?.baz) { // ... }
另一个新特性是Nullish Coalescing,例如:
let x = foo ?? bar(); // return foo if it's not null or undefined otherwise calculate bar
老方法:
let x = (foo !== null && foo !== undefined) ?
foo :
bar();
奖金
你可以使用
if(x === undefined)
All,
得票最多的答案,如果你在研究一个对象,就不适用了。在这种情况下,如果属性不存在,检查将不起作用。这就是我们案例中的问题:请看这个例子:
var x =
{ name: "Homer", LastName: "Simpson" };
var y =
{ name: "Marge"} ;
var z =
{ name: "Bart" , LastName: undefined} ;
var a =
{ name: "Lisa" , LastName: ""} ;
var hasLastNameX = x.LastName != null;
var hasLastNameY = y.LastName != null;
var hasLastNameZ = z.LastName != null;
var hasLastNameA = a.LastName != null;
alert (hasLastNameX + ' ' + hasLastNameY + ' ' + hasLastNameZ + ' ' + hasLastNameA);
var hasLastNameXX = x.LastName !== null;
var hasLastNameYY = y.LastName !== null;
var hasLastNameZZ = z.LastName !== null;
var hasLastNameAA = a.LastName !== null;
alert (hasLastNameXX + ' ' + hasLastNameYY + ' ' + hasLastNameZZ + ' ' + hasLastNameAA);
结果:
true , false, false , true (in case of !=)
true , true, true, true (in case of !==) => so in this sample not the correct answer
plunkr链接:https://plnkr.co/edit/BJpVHD95FhKlpHp1skUE
我在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是否被定义
最简单的方法是使用:
import {isNullOrUndefined} from 'util';
比:
如果isNullOrUndefined (foo (!)