在Typescript中,这将显示一个错误,表示isNaN只接受数值

isNaN('9BX46B6A')

返回false,因为parseFloat('9BX46B6A')的值为9

isNaN(parseFloat('9BX46B6A'))

我仍然可以运行的错误显示在Visual Studio,但我想做的正确的方式。

目前,我已经写了这个修改后的函数-

static isNaNModified = (inputStr: string) => {
    var numericRepr = parseFloat(inputStr);
    return isNaN(numericRepr) || numericRepr.toString().length != inputStr.length;
}

当前回答

这适用于特殊情况,例如空值

if(!isNaN(yourValue) && yourValue !== true && yourValue !== false) {
    // then it's a number
} else {
    // then it's not a number
}

其他回答

字符串是否可以解析为数字是运行时关心的问题。Typescript不支持这个用例,因为它关注的是编译时(而不是运行时)安全。

将字符串转换为数字的方法是使用number,而不是parseFloat。

Number('1234') // 1234
Number('9BX9') // NaN

如果你喜欢速记,你也可以使用一元加号运算符:

+'1234' // 1234
+'9BX9' // NaN

检查NaN时要小心(运算符===和!==不能像NaN那样工作)。使用:

 isNaN(+maybeNumber) // returns true if NaN, otherwise false

简单的回答:(注意空白和null)

isNaN(+'111') = false;
isNaN(+'111r') = true;
isNaN(+'r') = true;
isNaN(+'') = false;   
isNaN(null) = false;   

https://codepen.io/CQCoder/pen/zYGEjxd?editors=1111

这适用于特殊情况,例如空值

if(!isNaN(yourValue) && yourValue !== true && yourValue !== false) {
    // then it's a number
} else {
    // then it's not a number
}
 const isNumeric = (value: string): boolean =>
  !new RegExp(/[^\d]/g).test(value.trim());

如果你想允许小数点

   const isNumeric = (value: string): boolean =>
      !new RegExp(/[^\d.]/g).test(value.trim());