typescript 如何在打字稿中检查未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43716263/
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 07:42:57  来源:igfitidea点击:

How to check undefined in Typescript

typescript

提问by pushp

I am using this code to check undefined variable but it's not working.

我正在使用此代码来检查未定义的变量,但它不起作用。

var  uemail = localStorage.getItem("useremail");

if (typeof uemail === "undefined")
{
    alert('undefined');
}
else
{
    alert('defined');
}

回答by Garfty

You can just check for truthy on this:

您可以在此检查是否为真:

if(uemail) {
    console.log("I have something");
} else {
    console.log("Nothing here...");
}

Go and check out the answer from here: Is there a standard function to check for null, undefined, or blank variables in JavaScript?

去看看这里的答案:是否有一个标准函数来检查 JavaScript 中的 null、未定义或空白变量?

Hope this helps!

希望这可以帮助!

回答by ashish

In Typescript 2 you can use Undefined type to check for undefined values. So if you declare a variable as:

在 Typescript 2 中,您可以使用 Undefined 类型来检查未定义的值。因此,如果您将变量声明为:

let uemail : string | undefined;

Then you can check if the variable z is undefined as:

然后您可以检查变量 z 是否未定义为:

if(uemail === undefined)
{

}

回答by Nabin Kumar Khatiwada

It's because it's already null or undefined. Null or undefined does not have any type. You can check if it's is undefined first. In typescript (null == undefined)is true.

这是因为它已经为空或未定义。Null 或 undefined 没有任何类型。您可以先检查它是否未定义。在打字稿中(null == undefined)是正确的。

  if (uemail == undefined) {
      alert('undefined');
  } else {
      alert('defined');
  }

or

或者

  if (uemail == null) {
      alert('undefined');
  } else {
      alert('defined');
  }

回答by Sam Segers

It actually is working, but there is difference between nulland undefined. You are actually assigning to uemail, which would return a value or null in case it does not exists. As per documentation.

它实际上是有效的,但null和之间存在差异undefined。您实际上是在分配给 uemail,如果它不存在,它将返回一个值或 null。根据文档

For more information about the difference between the both of them, see this answer.

有关两者之间差异的更多信息,请参阅此答案

For a solution to this Garfty's answer may work, depending on what your requirement is. You may also want to have a look here.

对于此 Garfty 的答案的解决方案可能有效,具体取决于您的要求。您可能还想看看这里

回答by Paulus Potter

From Typescript 3.7 on, you can also use nullish coalescing:

从 Typescript 3.7 开始,您还可以使用无效合并:

let x = foo ?? bar();

Which is the equivalent for checking for null or undefined:

这相当于检查 null 或 undefined:

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

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing

While not exactly the same, you could write your code as:

虽然不完全相同,但您可以将代码编写为:

var uemail = localStorage.getItem("useremail") ?? alert('Undefined');

回答by Lucas

Adding this late answer to check for object.propertie that can help in some cases:

添加此迟到的答案以检查在某些情况下可以提供帮助的 object.properie:

Using a juggling-check, you can test both null and undefined in one hit:

使用杂耍检查,您可以一次性测试 null 和 undefined:

if (object.property == 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 的值才为真,对未定义的变量不会评估为真:

if (object.property === null) {

Typescript does NOT have a function to check if a variable is defined.

Typescript 没有检查变量是否已定义的功能。

回答by Ezio

NOT STRICTLY RELATED TO TYPESCRIPT

与打字稿没有严格关系

Just to add to all the above answers, we can also use the shorthand syntax

只是为了添加上述所有答案,我们还可以使用速记语法

var result = uemail || '';

This will give you the email if uemailvariable has some value and it will simply return an empty string if uemailvariable is undefined.

如果uemail变量具有某个值,这将为您提供电子邮件,如果变量uemail未定义,它将简单地返回一个空字符串。

This gives a nice syntax for handling undefined variables and also provide a way to use a default value in case the variable is undefined.

这为处理未定义的变量提供了一个很好的语法,并且还提供了一种在变量未定义的情况下使用默认值的方法。

回答by mtholen

Late to the story but I think some details are overlooked?

故事讲得很晚,但我认为有些细节被忽略了?

if you use

如果你使用

if (uemail !== undefined) {
  //some function
}

You are, technically, comparing variable uemailwith variable undefinedand, as the latter is not instantiated, it will give both type and value of 'undefined' purely by default, hence the comparison returns true. But it overlooks the potential that a variable by the name of undefinedmay actually exist -however unlikely- and would therefore then not be of type undefined. In that case, the comparison will return false.

从技术上讲,您正在将变量uemail与变量进行比较,undefined并且由于后者未实例化,因此默认情况下它将纯粹提供“未定义”的类型和值,因此比较返回 true。但它忽略了名称为 的变量undefined可能实际存在的可能性——尽管不太可能——因此不会是undefined类型。在这种情况下,比较将返回 false。

To be correct one would have to declare a constant of type undefinedfor example:

为了正确,必须声明一个类型为undefined的常量, 例如:

const _undefined: undefined

and then test by:

然后通过以下方式测试:

if (uemail === _undefined) {
  //some function
}

This test will return trueas uemailnow equals both value & type of _undefinedas _undefinedis now properly declared to be of type undefined.

本次测试将恢复trueuemail现在等于两个值的类型_undefined_undefined现在被正确声明为类型的不确定

Another way would be

另一种方式是

if (typeof(uemail) === 'undefined') {
  //some function
}

In which case the boolean return is based on comparing the two strings on either end of the comparison. This is, from a technical point of view, NOTtesting for undefined, although it achieves the same result.

在这种情况下,布尔返回基于比较两端的两个字符串。从技术角度来看,这不是测试未定义的,尽管它实现了相同的结果。

回答by Aryan Dixit

Use 'this' keyword to access variable. This worked for me

使用“this”关键字访问变量。这对我有用

var  uemail = localStorage.getItem("useremail");

if (typeof this.uemail === "undefined")
{
    alert('undefined');
}
else
{
    alert('defined');
}