It is not recommended to use the juggly-version of isNaN
, but I understand that you are using it to check both type and NaN
in your situation. While this method works with some juggling, a more reliable approach is to use type checking for types and NaN
checking specifically for NaN
s.
The initial console log outputs (1 - 3) demonstrate the behavior of isNaN
. In the following section (4 - 6), I demonstrate the inverted equivalents of type checks.
The last part (7 - 8) illustrates the implementation of type-and-NaN checking. By this point, you are no longer dependent on the questionable behavior of isNaN
and can switch to either the global version (since you now know you have a number) or the stricter Number.isNaN
version.
The belt-and-braces method does not trigger any compiler warnings.
const num = 1;
const str = 'string';
const obj = { key: 'value' };
// It technically functions but causes compiler warnings
console.log('1.', isNaN(num)); // false
console.log('2.', isNaN(str)); // true
console.log('3.', isNaN(obj)); // true
// More focused on types (note the results are opposite as I'm displaying 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
}
Below is a version that distinguishes between strings and 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