Why comparison with "!== NaN" is always true in TypeScript

Posted: (EET/GMT+2)

 

If you ever see your editor warn that an if condition is always true when checking for NaN, this is why.

In JavaScript and TypeScript, NaN has special comparison rules. It is not equal to anything, not even itself. For example:

NaN === NaN  // false!
NaN !== NaN  // true

Because of this, code like the following is broken, even though it looks reasonable at first glance. Consider the following example:

const value = Number(input);

if (value !== NaN) {
  useValue(value);
}

This if condition will always evaluate to true. Whether value is a valid number or NaN, the comparison still passes. TypeScript's control flow analysis detects this and correctly flags the if statement as unnecessary.

The correct way to check for NaN is to use Number.isNaN, like this:

const value = Number(input);

if (!Number.isNaN(value)) {
  useValue(value);
}

This works because Number.isNaN only returns true when the value is actually NaN, without applying any implicit type coercion.

Tip: avoid calling Number() multiple times. Convert once, store the result, and validate it.

Happy TypeScripting!