Josh Josh - 1 year ago 467
TypeScript Question

Easiest way to check for null and empty string on a typescript number

I'm surprised this question hasn't been asked, so maybe I'm overlooking the obvious. I have a form field that is supposed to be a number. Its starting value is null, but once a number is entered and cleared, its an empty string. It looks like javascript treats "" like 0 for numeric purposes.

So, instead of saying...

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

Is there a way to extend the TypeScript number type to have a IsNullOrEmpty() method? Or something similar that would simplify this expression?

Answer Source

You can simply use typeof. It will check undefined, null, 0 and "" also.

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