Using the juggly-version of isNaN
is discouraged, though I can see that you're using it to check both type and NaN
in your case. While this works with a bit of juggling, it is better to be a bit more belt-and-braces and use type checking to check types, and NaN
checking to check NaN
s.
The first chunk of console logs (1 - 3) are showing you the behaviour you are using from isNaN
. I use the (inverted) equivalents of type checks in the next section (4 - 6).
The final bit (7 - 8) shows the use of type-and-NaN checking. At this stage, you aren't relying on the sketchy behaviour of isNaN
and can use either the global version (as you are now certain you are using a number) or the Number.isNaN
version, which is tighter.
The belt-and-braces version has no compiler warnings.
const num = 1;
const str = 'string';
const obj = { key: 'value' };
// Technically works, but compiler warnings
console.log('1.', isNaN(num)); // false
console.log('2.', isNaN(str)); // true
console.log('3.', isNaN(obj)); // true
// A bit more type-ish (note the results are inverted as I'm showing the "positive" test
console.log('4.', typeof num === 'number'); // true
console.log('5.', typeof str === 'number'); // false
console.log('6.', typeof obj === 'number'); // false
const a = 1;
if (typeof a === 'number') {
console.log('7a.', isNaN(a)); // false
console.log('7b.', Number.isNaN(a)); // false
}
const b = NaN;
if (typeof b === 'number') {
console.log('8a.', isNaN(b)); // true
console.log('8b.', Number.isNaN(b)); // true
}
Here is a version that sorts out the strings from the numbers:
function stringNumberCheck(strNum: string | number) : boolean {
const numeric = +strNum;
return (typeof numeric === 'number' && !Number.isNaN(numeric));
}
console.log('1:', stringNumberCheck(1)); // true
console.log("'100':", stringNumberCheck('100')); // true
console.log("'Hello':", stringNumberCheck('Hello')); // false
Demo
"use strict";
function stringNumberCheck(strNum) {
const numeric = +strNum;
return (typeof numeric === 'number' && !Number.isNaN(numeric));
}
console.log('1:', stringNumberCheck(1)); // true
console.log("'100':", stringNumberCheck('100')); // true
console.log("'Hello':", stringNumberCheck('Hello')); // false