Sometimes, we want to fix isNan only accepting a number with TypeScript.
In this article, we’ll look at how to fix isNan only accepting a number with TypeScript.
How to fix isNan only accepting a number with TypeScript?
To fix isNan only accepting a number with TypeScript, we should remove isNaN with checking the variable’s type with the typeof operator and replace isNaN with Number.isNaN and Number.
For instance, we write
if (typeof expectedValue === "string" && !Number.isNaN(Number(expectedValue))) {
expectedValue = Number(expectedValue);
}
to use typeof expectedValue === "string" to check if expectedValue is a string.
Then we try to convert expectedValue to a number with Number(expectedValue).
And finally we call Number.isNaN to check if the value returned by Number is NaN or not.
Conclusion
To fix isNan only accepting a number with TypeScript, we should remove isNaN with checking the variable’s type with the typeof operator and replace isNaN with Number.isNaN and Number.