Typescript: check string for number

I am new to web development and in my function I want to check if the given string value is a number. If the string is not a valid number, I want to return null.

The following actions are performed for all cases, except when the string is "0", in which case it returns null.

parseInt(columnSortSettings[0]) || null; 

How to prevent this. Obviously, parseInt does not consider 0 to be an integer!

+8
javascript typescript
source share
3 answers

Since 0 acts like false, you can use isNaN() in this case

 var res = parseInt(columnSortSettings[0], 10); return isNaN(res) ? null : res; 
+9
source share

This is because you are basically testing 0, which is also not true. You can do

 var n = columnSortSettings[0]; if(parseInt(n, 10) || n === '0'){ //... } 

You can also check the number instead

 if(typeof(parseInt(n, 10)) === 'number'){ //... } 

But beware of the reason

 typeof Infinity === 'number'; typeof NaN === 'number'; 
+4
source share

You can use the isNumeric operator from the rxjs library (import rxjs / util / isNumeric

0
source share

All Articles