You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何禁止在非数字类型上调用Number.isNaN?求ESLint或替代方案

禁止非数字类型调用Number.isNaN的解决方案

针对你遇到的直接用Number.isNaN处理非数字类型导致的bug,以下是几种无需覆盖Airbnb ESLint规则、支持自动修复的可行方案:

一、ESLint no-restricted-properties 规则(基础限制)

这个规则可以精准限制Number.isNaN的调用,不会干扰Airbnb已有的no-restricted-syntax配置,配置如下:

{
  "rules": {
    "no-restricted-properties": [
      "error",
      {
        "object": "Number",
        "property": "isNaN",
        "message": "禁止直接调用Number.isNaN,请先将变量转为数字类型,或使用自定义isNaN方法"
      }
    ]
  }
}

当代码中出现Number.isNaN()调用时,ESLint会直接抛出错误提示,强制开发者修正。

二、自动修复+自定义严格类型isNaN方法

如果需要让ESLint自动将Number.isNaN替换为带数字转换的自定义方法,可配合eslint-plugin-replace实现:

  1. 安装插件:
npm install eslint-plugin-replace --save-dev
  1. ESLint配置:
{
  "plugins": ["replace"],
  "rules": {
    "no-restricted-properties": [
      "error",
      {
        "object": "Number",
        "property": "isNaN",
        "message": "请使用自定义的MyUtils.isNaN方法"
      }
    ],
    "replace/replace": [
      "error",
      [
        {
          "from": "Number.isNaN\\((.*?)\\)",
          "to": "MyUtils.isNaN(Number($1))",
          "message": "自动替换为带数字转换的严格类型isNaN方法"
        }
      ]
    ]
  }
}
  1. 编写自定义严格类型的MyUtils.isNaN:
// src/utils/MyUtils.js
export const isNaN = (value) => {
  // 可选:添加类型校验,非数字直接抛出错误
  if (typeof value !== 'number') {
    throw new Error('isNaN仅接受数字类型参数');
  }
  return Number.isNaN(value);
};

执行eslint --fix时,所有Number.isNaN(someVar)会自动替换为MyUtils.isNaN(Number(someVar)),彻底避免非数字类型传入的问题。

三、TypeScript类型约束方案(非ESLint)

如果项目使用TypeScript,可通过全局类型声明覆盖Number.isNaN的输入类型,从编译层面限制:

在项目的全局类型文件(如src/types/global.d.ts)中添加:

interface NumberConstructor {
  isNaN(value: number): boolean;
}

这样TypeScript编译器会在传入非数字类型时直接报错,且不会影响npm依赖包中Number.isNaN的正常调用(依赖的类型不受你的全局声明影响)。

四、折中方案:扩展Airbnb的no-restricted-syntax规则

若坚持使用no-restricted-syntax,可在保留Airbnb原有规则的基础上追加配置,而非直接覆盖:

{
  "extends": ["airbnb"],
  "rules": {
    "no-restricted-syntax": [
      "error",
      // 继承Airbnb的所有原有规则项
      ...require('eslint-config-airbnb/rules/style').rules['no-restricted-syntax'][1],
      {
        "message": "禁止直接调用Number.isNaN,请使用带数字转换的自定义方法",
        "selector": "MemberExpression[object.name='Number'][property.name='isNaN']"
      }
    ]
  }
}

此方案既保留Airbnb的代码风格约束,又实现了对Number.isNaN的调用限制。

内容的提问来源于stack exchange,提问作者Alex von Brandenfels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 00:05:41