【问题标题】:Easiest way to check for null and empty string on a TypeScript number检查 TypeScript 数字上的 null 和空字符串的最简单方法
【发布时间】:2016-12-27 16:03:08
【问题描述】:

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

所以,与其说...

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

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


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

if (this.RetailPrice) {

}

【问题讨论】:

  • 你如何设置this.RetailPrice的值?
  • 在输入(类型=数字)上与 Angular 的 ng-model 绑定。我将它定义为我的控制器中的一个数字(用 TypeScript 编写)。

标签: typescript


【解决方案1】:

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

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

【讨论】:

  • 你的代码和简单的 if (RetailPrice) 有什么区别?
  • if(RetailPrice) 如果变量 RetailPrice 从未被声明会抛出一个 JavaScript 异常 - if(typeof RetailPrice!='undefined' && RetailPrice) 会避免这种情况。
  • 您不应该使用 !== 进行此字符串比较吗?
  • 投反对票。 1. 使用strict 检查来避免javascripts "to falsy" 类型转换 2. 在声明之前使用变量时,typescript 不会编译。
  • 这是错误的答案,它不适用于字符串。 TS 抛出异常:类型 'string' 不可分配给类型 'boolean'。
【解决方案2】:

也排除空白字符串

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

【讨论】:

    【解决方案3】:

    数字字段需要一些不同的条件: if (typeof(numValue) === 'undefined' || numValue == null) { ... }

    【讨论】:

      【解决方案4】:

      对于希望通常区分虚假和非虚假并且愿意安装(小)包的打字稿用户,我发现utility-types 非常有用。

      import { isFalsy } from 'utility-types'
      
      if (!isFalsy(foo)) {
        // do something with foo, which you (and the compiler)
        // know is not false | "" | 0 | null | undefined
      }
      

      【讨论】:

        猜你喜欢
        • 2011-12-28
        • 2012-07-13
        • 2017-11-25
        • 2013-11-12
        • 1970-01-01
        • 2010-11-17
        • 2011-01-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多