在 Typescript 中处理 null >= 0

Handle null >= 0 in Typescript

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

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

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

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

另一种方法是使用 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

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

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

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

您可以使用 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

在JavaScript中,我常用的是:

`${value}` >= 0

// or

parseInt(value) >= 0

在 TypeScript 中,您最有可能使用:

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