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.

JavaScript

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:

JavaScript

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:

JavaScript

Playground Link

Or extracted on its own to just reduce the nesting:

JavaScript

Playground Link

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