Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(eslint-plugin): [prefer-return-this-type] add a new rule (#3228)
- Loading branch information
Showing
7 changed files
with
596 additions
and
0 deletions.
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.