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

如果 var和= 0; var x;

那么,这个呢? 和+ = (x | 0);

字符串是否可以解析为数字是运行时关心的问题。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, () => {}]