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
  • Loading branch information
rafaelss95 committed Sep 12, 2021
1 parent 4a88de2 commit 4a3a163
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
14 changes: 8 additions & 6 deletions packages/eslint-plugin/src/rules/prefer-return-this-type.ts
Original file line number Diff line number Diff line change
@@ -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 @@ -147,12 +147,14 @@ export default createRule({
}

if (isFunctionReturningThis(originalFunc, originalClass)) {
const node =
classNameRef.parent?.type === AST_NODE_TYPES.TSTypeReference
? classNameRef.parent
: classNameRef;
context.report({
node: classNameRef,
node,
messageId: 'useThisType',
fix(fixer) {
return fixer.replaceText(classNameRef, 'this');
},
fix: fixer => fixer.replaceText(node, 'this'),
});
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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 4a3a163

Please sign in to comment.