typescript 有没有办法同时检查“null”和“undefined”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28975896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:36:54  来源:igfitidea点击:

Is there a way to check for both `null` and `undefined`?

typescriptnull-check

提问by David Liu

Since TypeScript is strongly-typed, simply using if () {}to check for nulland undefineddoesn't sound right.

由于 TypeScript 是强类型的,因此仅if () {}用于检查null并且undefined听起来不正确。

Does TypeScript have any dedicated function or syntax sugar for this?

TypeScript 是否有任何专用的函数或语法糖?

回答by Fenton

Using a juggling-check, you can test both nulland undefinedin one hit:

使用杂耍检查,你可以测试nullundefined一重击:

if (x == null) {

If you use a strict-check, it will only be true for values set to nulland won't evaluate as true for undefined variables:

如果您使用严格检查,它只会对设置为 true 的值成立,null而对于未定义的变量则不会评估为 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"

“a == 空”

“a 未定义”

“b == 空”

“b === 空”

回答by Ramazan Sa??r

if( value ) {
}

will evaluate to trueif valueis not:

将评估为trueifvalue不是:

  • null
  • undefined
  • NaN
  • empty string ''
  • 0
  • false
  • null
  • undefined
  • NaN
  • 空字符串 ''
  • 0
  • false

typescript includes javascript rules.

打字稿包括 javascript 规则。

回答by basarat

Does TypeScript has dedicated function or syntax sugar for this

TypeScript 有专门的函数或语法糖吗?

TypeScript fully understands the JavaScript version which is something == null.

TypeScript 完全理解 JavaScript 版本,即something == null.

TypeScript will correctly rule out both nulland undefinedwith such checks.

TypeScript 会正确地排除这两种情况,nullundefined进行此类检查。

More

更多的

https://basarat.gitbook.io/typescript/recap/null-undefined

https://basarat.gitbook.io/typescript/recap/null-undefined

回答by Juangui Jordán

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
  • checking if (a != null) is right to know if a is defined
  • checking if (a) is wrong to know if a is defined
  • 检查 if (a == null) 是否正确知道 a 是否为空或未定义
  • 检查 (a != null) 是否正确知道是否定义了 a
  • 检查 (a) 是否错误以了解 a 是否已定义

回答by Ahmed Kamal

I think this answer needs an update, check the edit history for the old answer.

我认为这个答案需要更新,检查旧答案的编辑历史。

Basically, you have three deferent cases null, undefined, and undeclared, see the snippet below.

基本上,您有三种不同的情况 null、undefined 和 undeclared,请参阅下面的代码段。

// bad-file.ts
console.log(message)

You'll get an error says that variable messageis undefined (aka undeclared), of course, the Typescript compiler shouldn't let you do that but REALLY nothing can prevent you.

你会得到一个错误,说变量message未定义(也就是未声明),当然,Typescript 编译器不应该让你这样做,但真的没有什么可以阻止你。

// evil-file.ts
// @ts-gnore
console.log(message)

The compiler will be happy to just compile the code above. So, if you're sure that all variables are declared you can simply do that

编译器会很乐意只编译上面的代码。所以,如果你确定所有的变量都被声明了,你可以简单地做到这一点

if ( message != null ) {
    // do something with the message
}

the code above will check for nulland undefined, BUT in case the messagevariable may be undeclared (for safety), you may consider the following code

上面的代码将检查nullundefined,但如果message变量可能未声明(为了安全),您可以考虑以下代码

if ( typeof(message) !== 'undefined' && message !== null ) {
    // message variable is more than safe to be used.
}

Note: the order here typeof(message) !== 'undefined' && message !== nullis very important you have to check for the undefinedstate first atherwise it will be just the same as message != null, thanks @Jaider.

注意:这里的顺序typeof(message) !== 'undefined' && message !== null非常重要,您必须先检查undefined状态,否则它将与 相同message != null,谢谢@Jaider。

回答by avi.elkharrat

You may want to try

你可能想尝试

if(!!someValue)

with !!.

!!.

Explanation

解释

The first !will turn your expression into a booleanvalue.

第一个!会将您的表达式转换为boolean值。

Then !someValueis trueif someValueis falsyand falseif someValueis truthy. This might be confusing.

然后!someValuetrueifsomeValuefalseifsomeValue。这可能令人困惑。

By adding another !, the expression is now trueif someValueis truthyand falseif someValueis falsy, which is much easier to manage.

通过添加另一个!,表达式现在是trueifsomeValuefalseifsomeValue,这更容易管理。

Discussion

讨论

Now, why do I bother myself with if (!!someValue)when something like if (someValue)would have give me the same result?

现在,if (!!someValue)当类似的东西if (someValue)会给我同样的结果时,我为什么要打扰自己呢?

Because !!someValueis precisely a boolean expression, whereas someValuecould be absolutely anything. This kind of expression will now alow to write functions (and God we need those) like:

因为!!someValue恰好是一个布尔表达式,而someValue绝对可以是任何东西。这种表达式现在可以用来编写函数(上帝,我们需要这些函数),例如:

isSomeValueDefined(): boolean {
  return !!someValue
}

instead of:

代替:

isSomeValueDefined(): boolean {
  if(someValue) {
    return true
  }
  return false
}

I hope it helps.

我希望它有帮助。

回答by Fateh Mohamed

In TypeScript 3.7we have now Optional chainingand Nullish Coalescingto check nulland undefinedin the same time, example:

TypeScript 3.7 中,我们现在有了Optional chainingNullish Coalescing来同时检查nullundefined,例如:

let x = foo?.bar.baz();

this code will check if foo is defined otherwise it will return undefined

此代码将检查 foo 是否已定义,否则将返回 undefined

old way:

旧方式

if(foo != null && foo != undefined) {
   x = foo.bar.baz();
} 

this:

这个:

let x = (foo === null || foo === undefined) ? undefined : foo.bar();

if (foo && foo.bar && foo.bar.baz) { // ... }

With optional chaining will be:

使用可选链接将是:

let x = foo?.bar();

if (foo?.bar?.baz) { // ... }

another new feature is Nullish Coalescing, example:

另一个新功能是Nullish Coalescing,例如:

let x = foo ?? bar(); // return foo if it's not null or undefined otherwise calculate bar

old way:

旧方法:

let x = (foo !== null && foo !== undefined) ?
foo :
bar();

回答by Sergei Panfilov

For Typescript 2.x.xyou should do it in a following way(using type guard):

因为Typescript 2.x.x您应该按以下方式进行操作(使用type guard):

tl;dr

tl;博士

function isDefined<T>(value: T | undefined | null): value is T {
  return <T>value !== undefined && <T>value !== null;
}


Why?

为什么?

In this way isDefined()will respect variable's type and the following code would know take this check in account.

以这种方式isDefined()将尊重变量的类型,并且以下代码将知道考虑此检查。

Example 1- basic check:

示例 1- 基本检查:

function getFoo(foo: string): void { 
  //
}

function getBar(bar: string| undefined) {   
  getFoo(bar); //ERROR: "bar" can be undefined
  if (isDefined(bar)) {
    getFoo(bar); // Ok now, typescript knows that "bar' is defined
  }
}

Example 2- types respect:

示例 2- 类型方面:

function getFoo(foo: string): void { 
  //
}

function getBar(bar: number | undefined) {
  getFoo(bar); // ERROR: "number | undefined" is not assignable to "string"
  if (isDefined(bar)) {
    getFoo(bar); // ERROR: "number" is not assignable to "string", but it's ok - we know it's number
  }
}

回答by artemitSoft

if(data){}

it's mean !data

这是意思!数据

  • null
  • undefined
  • false
  • ....
  • 空值
  • 不明确的
  • 错误的
  • ....

回答by artemitSoft

If you are using TypeScript, it is a better approach to let the compiler check for nulls and undefineds (or the possibility thereof), rather than checking for them at run-time. (If you do want to check at run-time, then as many answers indicate, just use value == null).

如果您使用的是 TypeScript,那么让编译器检查空值和未定义值(或其可能性)是一种更好的方法,而不是在运行时检查它们。(如果您确实想在运行时检查,那么正如许多答案所指示的那样,只需使用value == null)。

Use the compile option strictNullChecksto tell the compiler to choke on possible null or undefined values. If you set this option, and then there is a situation where you dowant to allow null and undefined, you can define the type as Type | null | undefined.

使用 compile 选项strictNullChecks告诉编译器阻塞可能的 null 或 undefined 值。如果你设置了这个选项,然后有你确实想要允许 null 和 undefined 的情况,你可以将类型定义为Type | null | undefined.