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

如何为TypeScript特定函数编写自定义ESLint规则强制传入类型参数

编写自定义ESLint规则强制特定函数传入类型参数

要实现强制useFormContext这类函数必须传入泛型类型参数的ESLint规则,你可以基于@typescript-eslint工具链来编写,步骤如下:

1. 环境准备

确保项目已安装必要依赖:

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

2. 编写自定义规则

在项目中创建自定义规则文件(比如eslint-rules/require-generic-type-for-functions.js),核心逻辑是识别目标函数的调用,并检查是否存在泛型参数:

module.exports = {
  meta: {
    type: 'problem',
    docs: {
      description: '强制特定函数调用时必须传入泛型类型参数',
      recommended: true,
    },
    fixable: null,
    schema: [
      {
        type: 'array',
        items: { type: 'string' },
        uniqueItems: true,
      },
    ],
  },
  create(context) {
    // 从规则配置中获取需要检查的函数名列表,默认包含useFormContext
    const targetFunctions = context.options[0] || ['useFormContext'];

    return {
      // 监听函数调用表达式
      CallExpression(node) {
        // 仅处理直接调用的标识符(排除obj.func()这类成员调用)
        if (node.callee.type !== 'Identifier') return;

        const functionName = node.callee.name;
        // 判断是否是目标函数
        if (!targetFunctions.includes(functionName)) return;

        // 检查是否存在泛型类型参数
        if (!node.typeArguments) {
          context.report({
            node: node.callee,
            message: `调用 \`${functionName}\` 时必须传入泛型类型参数`,
          });
        }
      },
    };
  },
};

3. 配置ESLint使用自定义规则

在项目根目录的.eslintrc.js中添加规则配置:

module.exports = {
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  rules: {
    // 启用自定义规则,并可指定额外的目标函数
    'your-plugin/require-generic-type-for-functions': ['error', ['useFormContext', 'anotherTargetFunction']],
  },
  overrides: [
    {
      files: ['*.ts', '*.tsx'],
      parserOptions: {
        ecmaFeatures: { jsx: true },
        project: './tsconfig.json',
      },
    },
  ],
  // 指定自定义规则所在目录
  rulesDirectory: ['./eslint-rules'],
};

4. 测试规则

编写测试代码验证效果:

// 会触发ESLint错误
const form = useFormContext();

// 符合要求,不会触发错误
const form = useFormContext<MyFormType>();

运行ESLint检查时,未传入泛型参数的函数调用会被标记为错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:25:20