New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(eslint-plugin): [prefer-return-this-type] add a new rule #3228
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
ee36cf9
feat(eslint-plugin): [prefer-return-this-type] prototype
Zzzen d4d5a0a
feat(eslint-plugin): [prefer-return-this-type] update tests and doc
Zzzen 698a787
feat(eslint-plugin): [prefer-return-this-type] add tests and handle C…
Zzzen 59af3dd
feat(eslint-plugin): [prefer-return-this-type] fix arrow function
Zzzen b3a5230
feat(eslint-plugin): [prefer-return-this-type] add test
Zzzen 8131158
feat(eslint-plugin): [prefer-return-this-type] update doc and test
Zzzen 31ef41e
Apply suggestions from code review
Zzzen 059f7f4
feat(eslint-plugin): [prefer-return-this-type] error on more cases
Zzzen e400889
Merge remote-tracking branch 'origin/master' into this-type
Zzzen d19f340
feat(eslint-plugin): [prefer-return-this-type] regenerate docs and co…
Zzzen a84ef21
feat(eslint-plugin): [prefer-return-this-typetrigger CI
Zzzen 52df4db
Merge branch 'master' into this-type
bradzacher File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
90 changes: 90 additions & 0 deletions
90
packages/eslint-plugin/docs/rules/prefer-return-this-type.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
# Enforce that `this` is used when only `this` type is returned (`prefer-return-this-type`) | ||
|
||
[Method chaining](https://en.wikipedia.org/wiki/Method_chaining) is a common pattern in OOP languages and TypeScript provides a special [polymorphic this type](https://www.typescriptlang.org/docs/handbook/2/classes.html#this-types). | ||
If any type other than `this` is specified as the return type of these chaining methods, TypeScript will fail to cast it when invoking in subclass. | ||
|
||
```ts | ||
class Animal { | ||
eat(): Animal { | ||
console.log("I'm moving!"); | ||
return this; | ||
} | ||
} | ||
|
||
class Cat extends Animal { | ||
meow(): Cat { | ||
console.log('Meow~'); | ||
return this; | ||
} | ||
} | ||
|
||
const cat = new Cat(); | ||
// Error: Property 'meow' does not exist on type 'Animal'. | ||
// because `eat` returns `Animal` and not all animals meow. | ||
cat.eat().meow(); | ||
|
||
// the error can be fixed by removing the return type of `eat` or use `this` as the return type. | ||
class Animal { | ||
eat(): this { | ||
console.log("I'm moving!"); | ||
return this; | ||
} | ||
} | ||
|
||
class Cat extends Animal { | ||
meow(): this { | ||
console.log('Meow~'); | ||
return this; | ||
} | ||
} | ||
|
||
const cat = new Cat(); | ||
// no errors. Because `eat` returns `Cat` now | ||
cat.eat().meow(); | ||
``` | ||
|
||
Examples of **incorrect** code for this rule: | ||
|
||
```ts | ||
class Foo { | ||
f1(): Foo { | ||
return this; | ||
} | ||
f2 = (): Foo => { | ||
return this; | ||
}; | ||
f3(): Foo | undefined { | ||
return Math.random() > 0.5 ? this : undefined; | ||
} | ||
} | ||
``` | ||
|
||
Examples of **correct** code for this rule: | ||
|
||
```ts | ||
class Foo { | ||
f1(): this { | ||
return this; | ||
} | ||
f2() { | ||
return this; | ||
} | ||
f3 = (): this => { | ||
return this; | ||
}; | ||
f4 = () => { | ||
return this; | ||
}; | ||
} | ||
|
||
class Base {} | ||
class Derived extends Base { | ||
f(): Base { | ||
return this; | ||
} | ||
} | ||
``` | ||
|
||
## When Not To Use It | ||
|
||
If you don't use method chaining or explicit return values, you can safely turn this rule off. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
178 changes: 178 additions & 0 deletions
178
packages/eslint-plugin/src/rules/prefer-return-this-type.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,178 @@ | ||
import { | ||
TSESTree, | ||
AST_NODE_TYPES, | ||
} from '@typescript-eslint/experimental-utils'; | ||
import { createRule, forEachReturnStatement, getParserServices } from '../util'; | ||
import * as ts from 'typescript'; | ||
|
||
type ClassLikeDeclaration = | ||
| TSESTree.ClassDeclaration | ||
| TSESTree.ClassExpression; | ||
|
||
type FunctionLike = | ||
| TSESTree.MethodDefinition['value'] | ||
| TSESTree.ArrowFunctionExpression; | ||
|
||
export default createRule({ | ||
name: 'prefer-return-this-type', | ||
defaultOptions: [], | ||
|
||
meta: { | ||
type: 'suggestion', | ||
docs: { | ||
description: | ||
'Enforce that `this` is used when only `this` type is returned', | ||
category: 'Best Practices', | ||
recommended: false, | ||
requiresTypeChecking: true, | ||
}, | ||
messages: { | ||
useThisType: 'use `this` type instead.', | ||
}, | ||
schema: [], | ||
fixable: 'code', | ||
}, | ||
|
||
create(context) { | ||
const parserServices = getParserServices(context); | ||
const checker = parserServices.program.getTypeChecker(); | ||
|
||
function tryGetNameInType( | ||
name: string, | ||
typeNode: TSESTree.TypeNode, | ||
): TSESTree.Identifier | undefined { | ||
if ( | ||
typeNode.type === AST_NODE_TYPES.TSTypeReference && | ||
typeNode.typeName.type === AST_NODE_TYPES.Identifier && | ||
typeNode.typeName.name === name | ||
) { | ||
return typeNode.typeName; | ||
} | ||
|
||
if (typeNode.type === AST_NODE_TYPES.TSUnionType) { | ||
for (const type of typeNode.types) { | ||
const found = tryGetNameInType(name, type); | ||
if (found) { | ||
return found; | ||
} | ||
} | ||
} | ||
|
||
return undefined; | ||
} | ||
|
||
function isThisSpecifiedInParameters(originalFunc: FunctionLike): boolean { | ||
const firstArg = originalFunc.params[0]; | ||
return ( | ||
firstArg && | ||
firstArg.type === AST_NODE_TYPES.Identifier && | ||
firstArg.name === 'this' | ||
); | ||
} | ||
|
||
function isFunctionReturningThis( | ||
originalFunc: FunctionLike, | ||
originalClass: ClassLikeDeclaration, | ||
): boolean { | ||
if (isThisSpecifiedInParameters(originalFunc)) { | ||
return false; | ||
} | ||
|
||
const func = parserServices.esTreeNodeToTSNodeMap.get(originalFunc); | ||
|
||
if (!func.body) { | ||
return false; | ||
} | ||
|
||
const classType = checker.getTypeAtLocation( | ||
parserServices.esTreeNodeToTSNodeMap.get(originalClass), | ||
) as ts.InterfaceType; | ||
|
||
if (func.body.kind !== ts.SyntaxKind.Block) { | ||
const type = checker.getTypeAtLocation(func.body); | ||
return classType.thisType === type; | ||
} | ||
|
||
let hasReturnThis = false; | ||
let hasReturnClassType = false; | ||
|
||
forEachReturnStatement(func.body as ts.Block, stmt => { | ||
const expr = stmt.expression; | ||
if (!expr) { | ||
return; | ||
} | ||
|
||
// fast check | ||
if (expr.kind === ts.SyntaxKind.ThisKeyword) { | ||
hasReturnThis = true; | ||
return; | ||
} | ||
|
||
const type = checker.getTypeAtLocation(expr); | ||
if (classType === type) { | ||
hasReturnClassType = true; | ||
return true; | ||
} | ||
|
||
if (classType.thisType === type) { | ||
hasReturnThis = true; | ||
return; | ||
} | ||
|
||
return; | ||
}); | ||
|
||
return !hasReturnClassType && hasReturnThis; | ||
} | ||
|
||
function checkFunction( | ||
originalFunc: FunctionLike, | ||
originalClass: ClassLikeDeclaration, | ||
): void { | ||
const className = originalClass.id?.name; | ||
if (!className) { | ||
return; | ||
} | ||
|
||
if (!originalFunc.returnType) { | ||
return; | ||
} | ||
|
||
const classNameRef = tryGetNameInType( | ||
className, | ||
originalFunc.returnType.typeAnnotation, | ||
); | ||
if (!classNameRef) { | ||
return; | ||
} | ||
|
||
if (isFunctionReturningThis(originalFunc, originalClass)) { | ||
context.report({ | ||
node: classNameRef, | ||
messageId: 'useThisType', | ||
fix(fixer) { | ||
return fixer.replaceText(classNameRef, 'this'); | ||
}, | ||
}); | ||
} | ||
} | ||
|
||
return { | ||
'ClassBody > MethodDefinition'(node: TSESTree.MethodDefinition): void { | ||
checkFunction(node.value, node.parent!.parent as ClassLikeDeclaration); | ||
}, | ||
'ClassBody > ClassProperty'(node: TSESTree.ClassProperty): 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); | ||
}, | ||
}; | ||
}, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
one easier way to do this is to use a stack to track your state.
It saves you doing manual traversal of the tree
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Cool, I haven't seen this pattern before, will try it.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is more complicated than I have expected. We may have functions inside methods and need to track them too.