How to Allow Numeric String With isNaN() When Using TypeScript?

Find out how you can allow numeric string as a value to isNaN() without TypeScript complaining

In TypeScript, the JavaScript isNaN() function is typed as:

declare function isNaN(number: number): boolean;

Therefore, if you pass a value to isNaN() that's not a number, then TypeScript would complain. For example:

const numericVal: string | number = '123';

// Error: Argument of type 'string' is not assignable to parameter of type 'number'.

To fix this, you can use the Number constructor to try and convert a value into a number. If a non-numeric value is encountered it will result in NaN. Consider, for example, the following:

Number(123); // 123
Number('123'); // 123

Number('abc123'); // NaN
Number('abc123'); // NaN

// ...

With that information, you can simply use the Number constructor with isNaN() function, like so:

const numericVal: string | number = '123';


Now, TypeScript won't complain as you're explicitly converting non-numeric values into a number.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.