在 TypeScript 中检查一个值是否为 NaN
Check if a Value is NaN in TypeScript
要检查值是否为NaN
,请调用该Number.isNaN()
方法,将值作为参数传递给它。如果传入的值是且类型为,则该Number.isNaN
方法返回,否则返回。true
NaN
number
false
const val = Number('hello'); console.log(val); // 👉️ NaN if (Number.isNaN(val)) { // 👇️ this runs only if NaN and type of number console.log('Value is NaN'); }
我们使用
Number.isNaN
方法来检查一个值的类型是否为number
和 is NaN
。
如果传递给Number.isNaN
方法的值不是数字类型,则必须在传递给方法之前对其进行转换。
// 👇️ false, because passed in value is not a number console.log(Number.isNaN('test'));
该Number.isNaN
方法仅true
在传入值的类型为number
且 为时返回NaN
。
// 👇️ true console.log(Number.isNaN(Number('test')));
在检查 时永远不要尝试使用相等运算符,因为它在 Javascript(和 TypeScript)中并不等于,NaN
这看起来可能令人困惑。NaN
NaN
// 👇️ don't do this console.log(Number.NaN === Number.NaN); // 👉️ false
NaN
是 JavaScript(和 TypeScript)中唯一不等于自身的值。只有满足以下条件Number.isNaN
才会返回:true
- 该值是类型
number
- 价值是
NaN
以下所有示例都返回false
.
console.log(Number.isNaN('hello')); // 👉️ false console.log(Number.isNaN([])); // 👉️ false console.log(Number.isNaN({})); // 👉️ false console.log(Number.isNaN(undefined)); // 👉️ false console.log(Number.isNaN(null)); // 👉️ false
该Number.isNaN
功能非常容易实现。
function isNaN(input: unknown) { return typeof input === 'number' && input !== input; }
The function takes a parameter of type unknown
, checks whether it is a
number
and is not equal to itself.
NaN
is the only value in TypeScript that is not equal to itself this is sufficient to determine whether the user input is NaN
.You might also see examples online that use the older
isNaN
function.
This is generally a bad practice, because the isNaN
method is very
unintuitive.
If the argument provided to the isNaN
method is not of type number
, the
method coerces the value to a number
, before checking if it’s NaN
.
This is different from the Number.isNaN
method, which doesn’t coerce the
passed in value.
幸运的是,在 TypeScript 中,该isNaN
函数的类型是采用类型参数number
,因此搬起石头砸自己脚的难度要大得多。
通常建议不要使用超出其需要的方法,这可能会让您大吃一惊,并导致难以跟踪应用程序中的错误。