MST

星途 面试题库

面试题:TypeScript集成ESLint类型检查规则的自定义配置

假设在一个大型TypeScript项目中,默认的ESLint类型检查规则无法满足对特定模块的类型严格性要求,你将如何通过自定义配置ESLint规则来实现对该模块更严格的类型检查,例如确保某个函数的参数必须是特定类型的对象且包含特定属性。请写出具体步骤和关键配置代码。
42.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 安装必要插件

    • 首先确保项目中安装了eslint@typescript-eslint/parser以及@typescript-eslint/eslint-plugin。如果没有安装,可以使用以下命令:
    npm install eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
    
  2. 创建或编辑.eslintrc.json文件

    • 在项目根目录下找到.eslintrc.json文件,如果不存在则创建一个。
    • 配置parser@typescript-eslint/parser,并添加@typescript-eslint插件:
    {
      "parser": "@typescript-eslint/parser",
      "plugins": ["@typescript-eslint"],
      "rules": {}
    }
    
  3. 自定义规则

    • 要确保某个函数的参数必须是特定类型的对象且包含特定属性,可以自定义一个规则。这里借助@typescript-eslint/ban-types规则进行扩展。假设我们要检查一个名为myFunction的函数,其参数必须是包含specificProp属性的对象。
    • 首先在项目中创建一个自定义规则文件,例如rules/my - custom - rule.ts
    import { AST_NODE_TYPES } from '@typescript-eslint/experimental-utils';
    import { ESLintUtils } from '@typescript-eslint/experimental-utils';
    
    const createRule = ESLintUtils.RuleCreator(() => '');
    
    export const myCustomRule = createRule({
      name: 'function - param - must - have - specific - prop',
      meta: {
        type: 'problem',
        docs: {
          description: 'Ensures a function parameter has a specific property',
          recommended: 'error'
        },
        messages: {
          missingProp: 'The parameter of myFunction must have a "specificProp" property'
        },
        schema: []
      },
      defaultOptions: [],
      create(context) {
        return {
          CallExpression(node) {
            const callee = node.callee;
            if (
              callee.type === AST_NODE_TYPES.Identifier &&
              callee.name ==='myFunction'
            ) {
              const arg = node.arguments[0];
              if (
                arg &&
                arg.type === AST_NODE_TYPES.ObjectExpression &&
                arg.properties.every(prop => prop.key.name!=='specificProp')
              ) {
                context.report({
                  node: arg,
                  messageId:'missingProp'
                });
              }
            }
          }
        };
      }
    });
    
  4. .eslintrc.json中启用自定义规则

    • 回到.eslintrc.json文件,在rules中添加自定义规则:
    {
      "parser": "@typescript-eslint/parser",
      "plugins": ["@typescript-eslint"],
      "rules": {
        "function - param - must - have - specific - prop": "error"
      }
    }
    
  5. 配置针对特定模块

    • 如果只想对特定模块应用此规则,可以使用eslint - ignore或者在特定模块顶部添加注释来控制。例如,在特定模块顶部添加:
    /* eslint function - param - must - have - specific - prop: "error" */
    

    这样就只对该模块应用此自定义的严格类型检查规则。

    另外,如果项目使用的是ESLint配置文件的其他格式(如.eslintrc.js),配置思路类似,只是语法有所不同。例如.eslintrc.js的配置如下:

    const myCustomRule = require('./rules/my - custom - rule').myCustomRule;
    
    module.exports = {
      parser: '@typescript-eslint/parser',
      plugins: ['@typescript-eslint'],
      rules: {
        'function - param - must - have - specific - prop': myCustomRule
      }
    };