面试题答案
一键面试-
安装必要插件:
- 首先确保项目中安装了
eslint
和@typescript-eslint/parser
以及@typescript-eslint/eslint-plugin
。如果没有安装,可以使用以下命令:
npm install eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
- 首先确保项目中安装了
-
创建或编辑
.eslintrc.json
文件:- 在项目根目录下找到
.eslintrc.json
文件,如果不存在则创建一个。 - 配置
parser
为@typescript-eslint/parser
,并添加@typescript-eslint
插件:
{ "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"], "rules": {} }
- 在项目根目录下找到
-
自定义规则:
- 要确保某个函数的参数必须是特定类型的对象且包含特定属性,可以自定义一个规则。这里借助
@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' }); } } } }; } });
- 要确保某个函数的参数必须是特定类型的对象且包含特定属性,可以自定义一个规则。这里借助
-
在
.eslintrc.json
中启用自定义规则:- 回到
.eslintrc.json
文件,在rules
中添加自定义规则:
{ "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"], "rules": { "function - param - must - have - specific - prop": "error" } }
- 回到
-
配置针对特定模块:
- 如果只想对特定模块应用此规则,可以使用
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 } };
- 如果只想对特定模块应用此规则,可以使用