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

如何用ESLint禁止调用特定接口返回的指定函数?

解决方案:检测调用特定库函数的ESLint自定义规则

核心思路

借助TypeScript的类型分析能力(通过@typescript-eslint工具链)编写自定义ESLint规则,精准识别调用来自someGenerator返回值的badFunc——无论用户是直接赋值变量还是立即解构,都能触发告警。

实现步骤

1. 安装依赖

确保项目已安装以下开发依赖:

npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin @typescript-eslint/utils

2. 编写自定义规则

在项目根目录创建eslint-rules/no-call-bad-func.js文件,内容如下:

const { ESLintUtils } = require('@typescript-eslint/utils');

module.exports = ESLintUtils.RuleCreator(() => '')({
  create(context) {
    const parserServices = ESLintUtils.getParserServices(context);
    const typeChecker = parserServices.program.getTypeChecker();

    return {
      CallExpression(node) {
        // 过滤非badFunc的调用
        if (node.callee.type !== 'Identifier' || node.callee.name !== 'badFunc') return;

        // 获取标识符对应的TypeScript节点与类型
        const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node.callee);
        const symbol = typeChecker.getTypeAtLocation(tsNode).getSymbol();
        if (!symbol) return;

        // 检查该函数是否属于SomeReturn接口的属性
        const declarations = symbol.getDeclarations();
        if (!declarations?.length) return;
        const decl = declarations[0];
        if (!(decl.parent?.kind === 'InterfaceDeclaration' && decl.parent.name.text === 'SomeReturn')) return;

        // 验证该接口是否由someGenerator作为返回类型
        const funcSymbols = typeChecker.getSymbolsWithName('someGenerator', false);
        for (const funcSymbol of funcSymbols) {
          const funcDecls = funcSymbol.getDeclarations();
          if (funcDecls?.some(fd => {
            if (fd.kind === 'FunctionDeclaration' || fd.kind === 'VariableDeclaration') {
              const returnType = typeChecker.getTypeOfSymbolAtLocation(funcSymbol, fd);
              return returnType.getSymbol()?.name === 'SomeReturn';
            }
            return false;
          })) {
            context.report({
              node,
              message: '禁止调用badFunc,该函数会抛出错误'
            });
            break;
          }
        }
      }
    };
  },
  meta: {
    type: 'problem',
    docs: {
      description: '禁止调用来自someGenerator的badFunc',
      recommended: true
    },
    schema: []
  },
  name: 'no-call-bad-func',
  defaultOptions: []
});

3. 配置ESLint

修改项目根目录的.eslintrc.js,引入自定义规则并启用TypeScript类型检查:

module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: './tsconfig.json', // 必须指定tsconfig以获取类型信息
    sourceType: 'module'
  },
  plugins: ['@typescript-eslint'],
  rules: {
    './eslint-rules/no-call-bad-func': 'error' // 启用自定义规则,设为error级别触发告警
  }
};

补充说明

  • 该规则依赖TypeScript类型信息,因此必须确保parserOptions.project指向有效的tsconfig.json,否则无法正常工作。
  • 若需支持JavaScript项目,可以调整规则逻辑,通过追踪变量的赋值来源(比如是否从someGenerator()的返回值中解构)实现检测,但准确性会略低于TypeScript版本,因为JS缺乏类型约束。

内容的提问来源于stack exchange,提问作者BjornSnoen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 14:40:13