在 TypeScript 数字上检查空字符串和空字符串的最简单方法

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

Easiest way to check for null and empty string on a TypeScript number

typescript

提问by Josh

I'm surprised this question hasn't been asked, so maybe I'm overlooking the obvious. I have a form field that is supposed to be a number. Its starting value is null, but once a number is entered and cleared, its an empty string. It looks like JavaScript treats "" like 0 for numeric purposes.

我很惊讶这个问题没有被问到,所以也许我忽略了显而易见的问题。我有一个应该是数字的表单域。它的起始值为空,但一旦输入并清除一个数字,它就是一个空字符串。出于数字目的,JavaScript 似乎将 "" 视为 0。

So, instead of saying...

所以,与其说...

if ((this.RetailPrice != null && this.RetailPrice != 0) || this.RetailPrice === 0) {
        return this.RetailPrice;
      }

Is there a way to extend the TypeScript number type to have a IsNullOrEmpty() method? Or something similar that would simplify this expression?

有没有办法将 TypeScript 数字类型扩展为具有 IsNullOrEmpty() 方法?或者类似的东西可以简化这个表达式?



Ultimately, I think I was looking for something as simple as...

最终,我想我正在寻找一些简单的东西......

if (this.RetailPrice) {

}

回答by Parveen Sachdeva

You can simply use typeof. It will check undefined, null, 0 and "" also.

您可以简单地使用 typeof。它也会检查 undefined、null、0 和 ""。

if(typeof RetailPrice!='undefined' && RetailPrice){
   return this.RetailPrice;
}

回答by Asanka Siriwardena

To excludes blank strings as well

也排除空字符串

if(this.retailPrice && this.retailPrice.trim()){
   //Implement your logic here
}