本文翻译自:Is there a way to check for both `null` and `undefined`?
Since TypeScript is strongly-typed, simply using if () {}
to check null and undefined doesn't sound right. 由于TypeScript是强类型的,因此仅使用if () {}
来检查null和undefined听起来并不正确。
Does TypeScript has dedicated function or syntax sugar for this? TypeScript是否为此具有专用功能或语法糖?
#1楼
参考:https://stackoom.com/question/1xZxA/有没有办法检查-null-和-undefined
#2楼
Does TypeScript has dedicated function or syntax sugar for this TypeScript是否为此具有专用功能或语法糖
No. I just do something == null
same as JavaScript. 不。我只是做something == null
与JavaScript相同。
#3楼
I always write it like this: 我总是这样写:
var foo:string;
if(!foo){
foo="something";
}
This will work fine and I think it's very readable. 这可以正常工作,我认为它非常可读。
#4楼
Using a juggling-check, you can test both null
and undefined
in one hit: 使用杂项检查,您可以在一次undefined
中同时测试null
和undefined
:
if (x == null) {
If you use a strict-check, it will only be true for values set to null
and won't evaluate as true for undefined variables: 如果使用严格检查,则仅对于设置为null
值才为true,而对于未定义的变量则为true:
if (x === null) {
You can try this with various values using this example: 您可以使用以下示例尝试各种值:
var a: number;
var b: number = null;
function check(x, name) {
if (x == null) {
console.log(name + ' == null');
}
if (x === null) {
console.log(name + ' === null');
}
if (typeof x === 'undefined') {
console.log(name + ' is undefined');
}
}
check(a, 'a');
check(b, 'b');
Output 输出量
"a == null" “一个==空”
"a is undefined" “一个未定义”
"b == null" “ b == null”
"b === null" “ b === null”
#5楼
I did different tests on the typescript playground: 我在打字稿游乐场进行了不同的测试:
http://www.typescriptlang.org/play/ 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);
gives: 给出:
a is null or undefined
b is null or undefined
c is defined
so: 所以:
- checking if (a == null) is right to know if a is null or undefined 检查(a == null)是否正确以知道a为null还是未定义
- checking if (a != null) is right to know if a is defined 检查(a!= null)是否正确以了解是否已定义a
- checking if (a) is wrong to know if a is defined 检查(a)是否错误以知道是否已定义a
#6楼
if(data){}
it's mean !data 意思是!数据
- null 空值
- undefined 未定义
- false 假
- .... ....