有没有办法检查`null`和`undefined`?

本文翻译自: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中同时测试nullundefined

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
  • .... ....
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值