Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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?


Ultimately, I think I was looking for something as simple as...

if (this.RetailPrice) {  } 
like image 606
Josh Avatar asked Aug 20 '16 17:08

Josh


People also ask

How do I check if a string is empty in TypeScript?

Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty. Copied!

How do I check if a string is empty or null?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

How do I check if a value is null in TypeScript?

We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.

Can a TypeScript number be null?

TypeScript has two special values for Null and Undefined. Both represent no value or absence of any value. The difference between Null & Undefined is subtle and confusing.


2 Answers

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

if(typeof RetailPrice!='undefined' && RetailPrice){    return this.RetailPrice; } 
like image 92
Parveen Sachdeva Avatar answered Oct 02 '22 16:10

Parveen Sachdeva


To excludes blank strings as well

if(this.retailPrice && this.retailPrice.trim()){     //Implement your logic here  }
like image 36
Asanka Siriwardena Avatar answered Oct 02 '22 15:10

Asanka Siriwardena