在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;
}

当前回答

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

如果你想允许小数点

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

其他回答

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

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

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

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

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

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

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

大多数情况下,我们想要检查的值是字符串或数字,所以这里是我使用的函数:

const isNumber = (n: string | number): boolean => 
    !isNaN(parseFloat(String(n))) && isFinite(Number(n));

Codesandbox测试。

const willBeTrue = [0.1, '1', '-1', 1, -1, 0, -0, '0', "-0", 2e2, 1e23, 1.1, -0.1, '0.1', '2e2', '1e23', '-0.1', ' 898', '080']

const willBeFalse = ['9BX46B6A', "+''", '', '-0,1', [], '123a', 'a', 'NaN', 1e10000, undefined, null, NaN, Infinity, () => {}]

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

if(!isNaN(yourValue) && yourValue !== true && yourValue !== false) {
    // then it's a number
} else {
    // then it's not a number
}
function isNumber(value: string | number): boolean
{
   return ((value != null) &&
           (value !== '') &&
           !isNaN(Number(value.toString())));
}