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'.
isNaN(numericVal);
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'; isNaN(Number(numericVal));
Now, TypeScript won't complain as you're explicitly converting non-numeric values into a number.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.