【问题标题】:Handle null >= 0 in Typescript在 Typescript 中处理 null >= 0
【发布时间】:2025-12-25 10:25:16
【问题描述】:

我有一个简单的检查,我想检查给定变量是否 >=0。

public print(value: any): void {
    if(value >= 0) {
      console.log('Greater than zero')
    }
  }

这里的问题是当传入变量的值为 null 时,它将变为真值并记录该语句。有没有一种干净的方法来避免它,但不添加额外的检查?

【问题讨论】:

  • 额外检查有什么问题? if(value !== null && value >= 0) {
  • Number(null) 计算结果为 0,因此任何巧妙的技巧都不会适用
  • 如果你想让你的同事向你的方向扔文具,这里有if(value?.valueOf() >= 0)
  • 检查一下if (typeof value === 'number' && value >= 0) 怎么样?
  • 只需使用parseInt 检查是否不是NaN,不要打扰

标签: javascript typescript logical-operators


【解决方案1】:

我不明白您为什么不想添加空检查。

另一种方法是使用number 而不是any,但它只有在您的ts.conf 启用严格的空检查时才有效。

function print(value: number): void {
    if(value >= 0) {
      console.log('Greater than zero')
    }
}

print(null) // won't compile with strict null checks

【讨论】:

    【解决方案2】:

    如果您的代码库不允许使用null,只需使用undefined 并使用隐式转换,如下所示:

    public print(value: any): void {
        if(value != undefined && value >= 0) {
            console.log('Greater than zero')
        }
    }
    

    这是因为null == undefined(双等号创建了类型转换,而三等号没有)。

    【讨论】:

      【解决方案3】:

      您可以使用type guard,这将确保编译器您处理的不是null,而是一个数字。此外,它会使代码更正确,因为value: any 这意味着你可能会得到一个布尔值或传入的字符串:

      public print(value: any): void {
        if (typeof value === "number") {
          //value is definitely a number and not null
          if (value >= 0) {
            console.log('Greater than zero')
          }
        }
      }
      

      Playground Link

      现在代码会专门验证您确实得到了一个数字,然后检查它是否大于或等于零。这意味着不会处理null 或非数字值。

      为简洁起见,类型保护条件可以与其他条件结合使用:

      public print(value: any): void {
        if (typeof value === "number" && value >= 0) {
          console.log('Greater than zero')
        }
      }
      

      Playground Link

      或单独提取以减少嵌套:

      public print(value: any): void {
        if (typeof value !== "number")
          return;
      
        //value is definitely a number and not null
        if (value >= 0) {
          console.log('Greater than zero')
        }
      }
      

      Playground Link

      【讨论】:

        【解决方案4】:

        在 JavaScript 中,我通常使用以下内容:

        `${value}` >= 0
        
        // or
        
        parseInt(value) >= 0
        

        在 TypeScript 中您最有可能使用:

        public print(value: any): void {
          if (+`${value}` >= 0) {
            console.log('Not less than zero')
          }
        }
        

        【讨论】: