Skip to content

Commit

Permalink
fix(eslint-plugin): [prefer-return-this-type] handle generics properl…
Browse files Browse the repository at this point in the history
…y in fixer (#3852)
  • Loading branch information
rafaelss95 committed Sep 21, 2021
1 parent ffdb5ff commit 9e98b8f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 16 deletions.
24 changes: 9 additions & 15 deletions packages/eslint-plugin/src/rules/prefer-return-this-type.ts
@@ -1,9 +1,9 @@
import {
TSESTree,
AST_NODE_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import { createRule, forEachReturnStatement, getParserServices } from '../util';
import * as ts from 'typescript';
import { createRule, forEachReturnStatement, getParserServices } from '../util';

type ClassLikeDeclaration =
| TSESTree.ClassDeclaration
Expand Down Expand Up @@ -40,13 +40,13 @@ export default createRule({
function tryGetNameInType(
name: string,
typeNode: TSESTree.TypeNode,
): TSESTree.Identifier | undefined {
): TSESTree.TSTypeReference | undefined {
if (
typeNode.type === AST_NODE_TYPES.TSTypeReference &&
typeNode.typeName.type === AST_NODE_TYPES.Identifier &&
typeNode.typeName.name === name
) {
return typeNode.typeName;
return typeNode;
}

if (typeNode.type === AST_NODE_TYPES.TSUnionType) {
Expand Down Expand Up @@ -130,29 +130,23 @@ export default createRule({
originalClass: ClassLikeDeclaration,
): void {
const className = originalClass.id?.name;
if (!className) {
return;
}

if (!originalFunc.returnType) {
if (!className || !originalFunc.returnType) {
return;
}

const classNameRef = tryGetNameInType(
const node = tryGetNameInType(
className,
originalFunc.returnType.typeAnnotation,
);
if (!classNameRef) {
if (!node) {
return;
}

if (isFunctionReturningThis(originalFunc, originalClass)) {
context.report({
node: classNameRef,
node,
messageId: 'useThisType',
fix(fixer) {
return fixer.replaceText(classNameRef, 'this');
},
fix: fixer => fixer.replaceText(node, 'this'),
});
}
}
Expand Down
@@ -1,5 +1,5 @@
import rule from '../../src/rules/prefer-return-this-type';
import { RuleTester, getFixturesRootDir } from '../RuleTester';
import { getFixturesRootDir, RuleTester } from '../RuleTester';

const rootPath = getFixturesRootDir();

Expand Down Expand Up @@ -281,6 +281,33 @@ class Foo {
return this;
}
}
}
`,
},
{
// https://github.com/typescript-eslint/typescript-eslint/issues/3842
code: `
class Animal<T> {
eat(): Animal<T> {
console.log("I'm moving!");
return this;
}
}
`,
errors: [
{
messageId: 'useThisType',
line: 3,
column: 10,
endColumn: 19,
},
],
output: `
class Animal<T> {
eat(): this {
console.log("I'm moving!");
return this;
}
}
`,
},
Expand Down

0 comments on commit 9e98b8f

Please sign in to comment.