-1

I want to check whether a string entered is NAN in typescript. Currently I am doing like

if (isNaN(parseInt(input))) return "It's not a number."

This works fine if I enter @@@@ or #### but if I enter "444@@@@", this is not working.

code1
  • 8,351
  • 8
  • 27
  • 31
  • This question has nothing to do with TypeScript, which is merely a typing layer on top of JavaScript and a transpiler. –  May 05 '17 at 01:14

1 Answers1

2

parseInt parses up to the first non-numeral in the input string, see MDN:

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

In this case, parseInt("444@@@@") === 444, and 444 is not NaN.

If you want to check if the entire string represents a valid number, use Number instead:

if (isNaN(Number(input))) return "It's not a number."

Alternatively, use the unary plus operator to force a type conversion to number (equivalent to calling Number):

if (isNaN(+input)) return "It's not a number."

EDIT: Actually, isNaN will do a type conversion anyway, so you could just as well call it directly:

if (isNaN(input)) return "It's not a number."
Mattias Buelens
  • 19,609
  • 4
  • 45
  • 51