Categories
TypeScript Answers

How to fix isNan only accepting a number with TypeScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *