TypeScript isNan only accepts a number
Solution 1:
I advise you to implement your code differently.
The reasons:
- It might be short, but it's not easy to understand what's going on
- Using
isNaN
isn't the best option here:isNaN("")
returnsfalse
as well
You better try to convert the value into a number and check if that's NaN
or not (as @smnbbrv wrote):
if (typeof expectedValue === "string" && !Number.isNaN(Number(expectedValue))) {
expectedValue = Number(expectedValue);
}
Edit
You can pass your value as any
:
isNaN(ctualValue as any)
To bypass the compiler check.
Solution 2:
You should not solve it because this is how JavaScript works.
Just cast the input to number first
Number("10") // 10
Number("abc") // NaN
and then check the result with the isNan function:
isNaN(Number("abc"))
Solution 3:
As ironically only numbers can be NaN
, you need to transform strings into numbers first.
A very simple way to do this is the unary plus operator.
So you can do a simple isNaN(+"10")
.
Keep in mind that thing like +""
, +" "
and +"\n"
are 0!