Check if String is a Valid Number in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 8, 2022

banner

Photo from Unsplash

Check if String is a Valid Number in TypeScript #

To check if a string is a valid number in TypeScript:

  1. Check that the string is not an empty string or contains only spaces.
  2. Pass the string to the Number.isNaN() method.
  3. If Number.isNaN returns false, the string is a valid number.
index.ts
function isNumber(str: string): boolean { if (typeof str !== 'string') { return false; } if (str.trim() === '') { return false; } return !Number.isNaN(Number(str)); } const str1 = '7'; const str2 = '7.3'; const str3 = ' '; const str4 = '123hello'; console.log(isNumber(str1)); // 👉️ true console.log(isNumber(str2)); // 👉️ true console.log(isNumber(str3)); // 👉️ false console.log(isNumber(str4)); // 👉️ false

We created a reusable function that takes a string and returns a boolean result for whether the string is a valid number or not.

We first check if the value passed to the function doesn't have a type of string, in which case we return false straight away.

When using TypeScript you can assume that the passed in value is going to be a string, but the check is just there for runtime safety.

Then, we check if the provided value is an empty string or contains only whitespace, in which case we also return false.

Finally, we use the Number.isNaN method to check if the string converted to a number is NaN (not a number).

We use the logical NOT (!) operator to negate the value returned from the Number.isNaN method.

The Number.isNaN method will return true if the passed in value is NaN (not a number) and its type is number, otherwise it returns false.

index.ts
console.log(Number.isNaN('hello')); // 👉️ false console.log(Number.isNaN(Number('hello'))); // 👉️ true

Our function checks if the passed in string is a valid number and not whether the passed in string is NaN when converted to a number, so we had to negate the call to the Number.isNaN method.

index.ts
console.log(!Number.isNaN(Number('hello'))); // 👉️ false console.log(!Number.isNaN(Number('17.5'))); // 👉️ true

If the call to the Number.isNaN() method returns false, then the passed in string is a valid number and we should return true.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.