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

当前回答

我会选择一个现有的和已经测试过的解决方案。例如,typescript中的rxjs:

function isNumeric(val: any): val is number | string {
  // parseFloat NaNs numeric-cast false positives (null|true|false|"")
  // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  // subtraction forces infinities to NaN
  // adding 1 corrects loss of precision from parseFloat (#15100)
  return !isArray(val) && (val - parseFloat(val) + 1) >= 0;
}

rxjs / isNumeric.ts

没有rxjs的isArray()函数,只有简化的类型:

function isNumeric(val: any): boolean {
  return !(val instanceof Array) && (val - parseFloat(val) + 1) >= 0;
}

您应该总是用您的用例来测试这些函数。如果您有特殊的值类型,这个函数可能不是您的解决方案。 你可以在这里测试这个函数。

结果是:

enum         : CardTypes.Debit   : true
decimal      : 10                : true
hexaDecimal  : 0xf10b            : true
binary       : 0b110100          : true
octal        : 0o410             : true
stringNumber : '10'              : true

string       : 'Hello'           : false
undefined    : undefined         : false
null         : null              : false
function     : () => {}          : false
array        : [80, 85, 75]      : false
turple       : ['Kunal', 2018]   : false
object       : {}                : false

如您所见,如果您将此函数用于枚举,则必须非常小心。

其他回答

function isNumber(value: string | number): boolean
{
   return ((value != null) &&
           (value !== '') &&
           !isNaN(Number(value.toString())));
}

考虑到你的变量可以是字符串、数字或任何类型——对于Angular/Typescript中的完整数字(非浮点数),你可以使用:

var isFullNumber: boolean = 
    Number.isInteger(Number(yourVariable)) && yourVariable !== null;

正如@tarrbal所指出的那样,我们不能使用just:

Number.isInteger(yourVariable);

要证明这一点,请检查以下三个测试:

let testVariables = [0, 1, "0", "1", "A", {}, -3, 0.1, NaN, null, undefined]; 

let isFullNumber: boolean;
let ix: number = 1;
testVariables.forEach(v => {
isFullNumber = Number.isInteger(v);                         // <---
console.log(ix++, ': ', v, isFullNumber);
})

console.log('--------------');

ix = 1;
testVariables.forEach(v => {
isFullNumber = Number.isInteger(Number(v));                 // <---
console.log(ix++, ': ', v, isFullNumber);
})

console.log('--------------');
ix = 1;
testVariables.forEach(v => {
isFullNumber = Number.isInteger(Number(v)) && v !== null;   // <---
console.log(ix++, ': ', v, isFullNumber);
})

这三个结果:

1   :       0           true
2   :       1           true
3   :       0           false <- would expect true
4   :       1           false <- would expect true
5   :       A           false
6   :       {}          false
7   :       -3          true
8   :       0.1         false
9   :       NaN         false
10  :       null        false
11  :       undefined   false
----------------------------
1   :       0           true
2   :       1           true
3   :       0           true
4   :       1           true
5   :       A           false
6   :       {}          false
7   :       -3          true
8   :       0.1         false
9   :       NaN         false
10  :       null        true <- would expect false
11  :       undefined   false
----------------------------
1   :       0           true
2   :       1           true
3   :       0           true
4   :       1           true
5   :       A           false
6   :       {}          false
7   :       -3          true
8   :       0.1         false
9   :       NaN         false
10  :       null        false
11  :       undefined   false

如果 var和= 0; var x;

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

我的简单解决方案是:

const isNumeric = (val: string) : boolean => {
   return !isNaN(Number(val));
}

// isNumberic("2") => true
// isNumeric("hi") => false;

我的解决方案:

 function isNumeric(val: unknown): val is string | number {
  return (
    !isNaN(Number(Number.parseFloat(String(val)))) &&
    isFinite(Number(val))
  );
}
// true
isNumeric("-10");
isNumeric("0");
isNumeric("0xff");
isNumeric("0xFF");
isNumeric("8e5");
isNumeric("3.1415");
isNumeric("+10");
isNumeric("144");
isNumeric("5");

// false
isNumeric("-0x42");
isNumeric("7.2acdgs");
isNumeric("");
isNumeric({});
isNumeric(NaN);
isNumeric(null);
isNumeric(true);
isNumeric(Infinity);
isNumeric(undefined);
isNumeric([]);
isNumeric("some string");