如何使用ESLint no-restricted-syntax规则禁止this作为函数及类方法返回类型?
用ESLint禁用
this作为函数/类方法的返回类型 要禁止将this关键字用作函数和类方法的返回类型,你可以利用ESLint的no-restricted-syntax规则,通过指定对应的AST(抽象语法树)节点选择器来实现。
配置步骤
- 确保ESLint支持TypeScript语法:如果你在TypeScript项目中使用,需配置
@typescript-eslint/parser作为解析器,并启用@typescript-eslint插件(未配置的话先补全这一步)。 - 添加
no-restricted-syntax规则配置:在你的ESLint配置文件(如.eslintrc.js或.eslintrc.json)中,加入以下规则:
module.exports = { parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], rules: { 'no-restricted-syntax': [ 'error', { selector: 'TSFunctionType > TSThisType, TSTypeAnnotation > TSThisType, ClassMethod > TSTypeAnnotation > TSThisType, FunctionDeclaration > TSTypeAnnotation > TSThisType, FunctionExpression > TSTypeAnnotation > TSThisType', message: '禁止使用`this`作为返回类型,请使用具体类型或类型别名替代' } ] } };
选择器说明
上述选择器针对不同场景的this返回类型进行拦截:
TSFunctionType > TSThisType:拦截函数类型定义中的this返回类型(如type Fn = () => this)TSTypeAnnotation > TSThisType:拦截普通函数返回类型中的thisClassMethod > TSTypeAnnotation > TSThisType:拦截类方法返回类型中的thisFunctionDeclaration > TSTypeAnnotation > TSThisType:拦截函数声明返回类型中的thisFunctionExpression > TSTypeAnnotation > TSThisType:拦截函数表达式返回类型中的this
示例代码
会触发错误的代码
class Example { // 类方法返回this类型,会被禁止 method(): this { return this; } } // 函数声明返回this类型,会被禁止 function foo(): this { return this; } // 函数表达式返回this类型,会被禁止 const bar = function(): this { return this; }; // 箭头函数返回this类型,会被禁止 const baz = (): this => { return this; };
允许的替代写法
class Example { // 使用类自身类型作为返回值 method(): Example { return this; } } // 使用具体类型或类型别名 type MyType = { /* ... */ }; function foo(): MyType { return {} as MyType; }
这样配置后,任何将this作为函数或类方法返回类型的代码都会被ESLint标记为错误,避免冗余的this返回类型定义。
内容的提问来源于stack exchange,提问作者olfek
相关产品推荐
相关产品推荐

