diff --git a/packages/eslint-plugin/src/rules/prefer-return-this-type.ts b/packages/eslint-plugin/src/rules/prefer-return-this-type.ts index 304f63dd1027..fff92141fe12 100644 --- a/packages/eslint-plugin/src/rules/prefer-return-this-type.ts +++ b/packages/eslint-plugin/src/rules/prefer-return-this-type.ts @@ -148,24 +148,27 @@ export default createRule({ } } + function checkProperty( + node: TSESTree.AccessorProperty | TSESTree.PropertyDefinition, + ): void { + if ( + !( + node.value?.type === AST_NODE_TYPES.FunctionExpression || + node.value?.type === AST_NODE_TYPES.ArrowFunctionExpression + ) + ) { + return; + } + + checkFunction(node.value, node.parent.parent); + } + return { + 'ClassBody > AccessorProperty': checkProperty, 'ClassBody > MethodDefinition'(node: TSESTree.MethodDefinition): void { - checkFunction(node.value, node.parent.parent as ClassLikeDeclaration); - }, - 'ClassBody > PropertyDefinition'( - node: TSESTree.PropertyDefinition, - ): void { - if ( - !( - node.value?.type === AST_NODE_TYPES.FunctionExpression || - node.value?.type === AST_NODE_TYPES.ArrowFunctionExpression - ) - ) { - return; - } - - checkFunction(node.value, node.parent.parent as ClassLikeDeclaration); + checkFunction(node.value, node.parent.parent); }, + 'ClassBody > PropertyDefinition': checkProperty, }; }, }); diff --git a/packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts b/packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts index 4a9262e92ce9..5b372350059f 100644 --- a/packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts +++ b/packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts @@ -79,6 +79,25 @@ class Derived extends Base { f(): Base { return this; } +} + `, + ` +class Foo { + accessor f = () => { + return this; + }; +} + `, + ` +class Foo { + accessor f = (): this => { + return this; + }; +} + `, + ` +class Foo { + f?: string; } `, ], @@ -108,6 +127,29 @@ class Foo { }, { code: ` +class Foo { + f = function (): Foo { + return this; + }; +} + `, + errors: [ + { + column: 20, + line: 3, + messageId: 'useThisType', + }, + ], + output: ` +class Foo { + f = function (): this { + return this; + }; +} + `, + }, + { + code: ` class Foo { f(): Foo { const self = this; @@ -200,6 +242,48 @@ class Foo { }, { code: ` +class Foo { + accessor f = (): Foo => { + return this; + }; +} + `, + errors: [ + { + column: 20, + line: 3, + messageId: 'useThisType', + }, + ], + output: ` +class Foo { + accessor f = (): this => { + return this; + }; +} + `, + }, + { + code: ` +class Foo { + accessor f = (): Foo => this; +} + `, + errors: [ + { + column: 20, + line: 3, + messageId: 'useThisType', + }, + ], + output: ` +class Foo { + accessor f = (): this => this; +} + `, + }, + { + code: ` class Foo { f1(): Foo | undefined { return this;