Skip to content
Advertisement

Handle null >= 0 in Typescript

I have a simple check where I want to check if the given variable is >=0.

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

The catch here is when the incoming variable has value null, then it will become truthy and log the statement. Is there a clean way to avoid it, but not adding extra checks?

Advertisement

Answer

You can employ a type guard that will assure the compiler that you’re not handling a null but a number. Moreover, it will make the code more correct, since with value: any this means you might get a boolean or a string passed in:

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

Now the code specifically verifies that you do get a number and then checks if it’s more than or equal to zero. This means that a null or a non-number value would not be processed.

The type guard condition can be combined with the other for brevity:

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

Playground Link

Or extracted on its own to just reduce the nesting:

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement