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

当前回答

这是我信赖的isNumber函数。明智地使用它

function isNumber(numStr: string) {
  return !isNaN(parseFloat(numStr)) && !isNaN(+numStr)
}

测试

it("test valid isNumber", () => {
  expect(isNumber("0")).toEqual(true)
  expect(isNumber("-1")).toEqual(true)
})

it("test invalid isNumber", () => {
  expect(isNumber('" 1000 "')).toEqual(false)
  expect(isNumber('" 100,00.00 "')).toEqual(false)
  expect(isNumber("100,00.00")).toEqual(false)
  expect(isNumber("")).toEqual(false)
  expect(isNumber(null as any as string)).toEqual(false)
  expect(isNumber("abc")).toEqual(false)
  expect(isNumber("10%")).toEqual(false)
  expect(isNumber("#10")).toEqual(false)
  expect(isNumber("2^10")).toEqual(false)
  expect(isNumber("2!")).toEqual(false)
  expect(isNumber("(10)")).toEqual(false)
  expect(isNumber("10px")).toEqual(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, () => {}]

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

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

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

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

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

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

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

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

如果 var和= 0; var x;

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