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) { }
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!
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.
We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.
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.
You can simply use typeof. It will check undefined, null, 0 and "" also.
if(typeof RetailPrice!='undefined' && RetailPrice){ return this.RetailPrice; }
To excludes blank strings as well
if(this.retailPrice && this.retailPrice.trim()){ //Implement your logic here }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With