TypeScript Check If String Is Number – 6 Proven Methods

When working with user input or data from external sources in TypeScript, I often need to verify if a string contains only numeric characters. This is a common requirement in form validation, data processing, and many other scenarios.

In this article, I’ll share several reliable methods I’ve used over my years of TypeScript development to check if a string is a number. All methods will have real examples. Let us start.

Method 1: Using the isNaN() Function

The best way to check if a string is a number in TypeScript is using the built-in isNaN() function, which stands for “is Not a Number.”

Here is an example and the complete TypeScript code.

function isStringNumber(value: string): boolean {
  // Using Number constructor to attempt conversion
  return !isNaN(Number(value)) && value.trim() !== '';
}

// Examples
console.log(isStringNumber("123"));     // true
console.log(isStringNumber("123.45"));  // true
console.log(isStringNumber("-123"));    // true
console.log(isStringNumber("abc"));     // false
console.log(isStringNumber(""));        // false
console.log(isStringNumber(" "));       // false

The isNaN() function attempts to convert the string to a number and returns true if the conversion fails. By adding the check for empty strings, we ensure that empty inputs aren’t considered valid numbers.

You can see the output in the screenshot below:

typescript check if string is number

Check out TypeScript keyof with Strings

Method 2: Using Regular Expressions

For more control over what constitutes a “numeric string,” I often use regular expressions. This approach is powerful when you need specific validation rules.

Here is an example.

function isStringNumber(value: string): boolean {
  // This regex checks for integers and floating-point numbers
  const numberPattern = /^-?\d+(\.\d+)?$/;
  return numberPattern.test(value);
}

// Examples
console.log(isStringNumber("123"));     // true
console.log(isStringNumber("123.45"));  // true
console.log(isStringNumber("-123"));    // true
console.log(isStringNumber("abc"));     // false
console.log(isStringNumber("123abc"));  // false
console.log(isStringNumber("123."));    // false

This regex pattern checks for optional negative sign, one or more digits, and optional decimal portion. It’s stricter than the isNaN() approach and rejects strings like “123.” (with a trailing period).

You can see the exact output in the screenshot below:

check if string is number typescript

Check out Multiline Strings in TypeScript

Method 3: Using parseInt() or parseFloat() With Type Checking

Another approach I use often involves the built-in parsing functions with additional type checking:

function isStringInteger(value: string): boolean {
  const num = parseInt(value, 10);
  return !isNaN(num) && num.toString() === value;
}

function isStringFloat(value: string): boolean {
  const num = parseFloat(value);
  return !isNaN(num) && num.toString() === value;
}

// For both integers and floats
function isStringNumber(value: string): boolean {
  const num = parseFloat(value);
  return !isNaN(num) && String(num) === value;
}

// Examples
console.log(isStringInteger("123"));    // true
console.log(isStringInteger("123.45")); // false
console.log(isStringFloat("123.45"));   // true

The key part here is comparing the parsed number converted back to a string with the original input. This ensures that the entire string is a valid number without any extra characters.

You can see the exact output in the screenshot below:

typescript check string is number

Check out Compare Strings in TypeScript

Method 4: Using Type Guards

In TypeScript, we can create custom type guards to check if a string is a number:

function isStringNumber(value: string): value is string {
  return !isNaN(Number(value)) && value.trim() !== '';
}

// Usage with type narrowing
function processInput(input: string) {
  if (isStringNumber(input)) {
    // TypeScript knows input is a numeric string here
    const num = Number(input);
    return num * 2;
  } else {
    return "Not a number";
  }
}

This approach leverages TypeScript’s type system to provide better type safety in your code. The value is string return type helps TypeScript understand that the string is specifically a numeric string.

Check out PowerShell Array of Strings

Method 5: Using JavaScript’s Unary Plus Operator

The unary plus operator (+) is a quick way to attempt number conversion in JavaScript:

function isStringNumber(value: string): boolean {
  // The unary plus operator attempts to convert to a number
  return !isNaN(+value) && value.trim() !== '';
}

// Examples
console.log(isStringNumber("123"));     // true
console.log(isStringNumber("123.45"));  // true
console.log(isStringNumber("-123"));    // true
console.log(isStringNumber("abc"));     // false

This method is similar to using Number() but with a more concise syntax. It’s my go-to approach for quick checks in smaller projects.

Check out Check If a String Is in an Enum in TypeScript

Method 6: Handling Special Number Formats

If you’re dealing with data that might contain formatted numbers (like currency or percentages), you might need a more flexible approach:

function isStringNumber(value: string): boolean {
  // Remove currency symbols, commas, percentage signs, etc.
  const cleanedValue = value.replace(/[$,€£%\s]/g, '');
  return !isNaN(Number(cleanedValue)) && cleanedValue.trim() !== '';
}

// Examples
console.log(isStringNumber("$1,234.56")); // true
console.log(isStringNumber("45%"));       // true
console.log(isStringNumber("1 234,56"));  // true (European format)

This method is particularly useful when working with user input in applications like budget trackers or tax calculators where numbers might come in with formatting.

You can see the exact output in the screenshot below:

ts check if string is number

Read Convert String to Enum in TypeScript

Real-World Example: Form Validation

Let’s look at a practical example where checking if a string is a number is essential – validating a US-based loan application form:

interface LoanApplication {
  fullName: string;
  loanAmount: string;
  annualIncome: string;
  socialSecurityNumber: string;
  zipCode: string;
}

function validateLoanApplication(application: LoanApplication): string[] {
  const errors: string[] = [];

  // Check if loan amount is a valid number
  if (!isStringNumber(application.loanAmount)) {
    errors.push("Loan amount must be a valid number");
  } else if (Number(application.loanAmount) <= 0) {
    errors.push("Loan amount must be greater than zero");
  }

  // Check if annual income is a valid number
  if (!isStringNumber(application.annualIncome)) {
    errors.push("Annual income must be a valid number");
  }

  // Check if ZIP code is a 5-digit number
  if (!/^\d{5}$/.test(application.zipCode)) {
    errors.push("ZIP code must be a 5-digit number");
  }

  // Check if SSN follows the pattern XXX-XX-XXXX
  if (!/^\d{3}-\d{2}-\d{4}$/.test(application.socialSecurityNumber)) {
    errors.push("Please enter a valid Social Security Number (XXX-XX-XXXX)");
  }

  return errors;
}

function isStringNumber(value: string): boolean {
  return !isNaN(Number(value)) && value.trim() !== '';
}

In this example, we’re validating a loan application by checking if the loan amount and annual income are valid numbers, while also performing specific validations for ZIP codes and Social Security Numbers.

Check out Convert String to Number in TypeScript

Choosing the Right Method

After working with TypeScript for over 6 years, I’ve found that the best method to use depends on your specific requirements:

  • For simple validation, the isNaN(Number(value)) approach works well
  • When you need more precise control, regular expressions are the way to go
  • If you’re working with formatted numbers, a cleaning step before validation is essential
  • For TypeScript-specific benefits, type guards provide additional type safety

I typically use the unary plus method (!isNaN(+value)) for most of my projects due to its simplicity and effectiveness.

In this tutorial, I explain various methods for checking if a string is a number in TypeScript.

I hope you found this guide helpful! Let me know if you have any questions or other methods you prefer for checking if a string is a number in TypeScript.

You may also like:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App