Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.8k
feat(eslint-plugin): add prefer-function-type rule#222
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
uniqueiniquity merged 7 commits intotypescript-eslint:masterfromuniqueiniquity:addCallableTypesFeb 8, 2019
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
7 commits Select commitHold shift + click to select a range
f8529f3
feat(eslint-plugin): add callable-types rule
a0411b6
fix: refine selector and ignore implements
65f56b8
fix: change rule name
c488ab5
Merge branch 'master' into addCallableTypes
uniqueiniquity958b75e
fix: update rule name change
258085e
Merge branch 'master' into addCallableTypes
JamesHenry22aa150
Merge branch 'master' into addCallableTypes
uniqueiniquityFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
1 change: 1 addition & 0 deletionspackages/eslint-plugin/README.md
This file contains hidden or 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
3 changes: 2 additions & 1 deletionpackages/eslint-plugin/ROADMAP.md
This file contains hidden or 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
57 changes: 57 additions & 0 deletionspackages/eslint-plugin/docs/rules/prefer-function-type.md
This file contains hidden or 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,57 @@ | ||
# Use function types instead of interfaces with call signatures (prefer-function-type) | ||
## Rule Details | ||
This rule suggests using a function type instead of an interface or object type literal with a single call signature. | ||
Examples of **incorrect** code for this rule: | ||
```ts | ||
interface Foo { | ||
(): string; | ||
} | ||
``` | ||
```ts | ||
function foo(bar: { (): number }): number { | ||
return bar(); | ||
} | ||
``` | ||
```ts | ||
interface Foo extends Function { | ||
(): void; | ||
} | ||
``` | ||
Examples of **correct** code for this rule: | ||
```ts | ||
interface Foo { | ||
(): void; | ||
bar: number; | ||
} | ||
``` | ||
```ts | ||
function foo(bar: { (): string; baz: number }): string { | ||
return bar(); | ||
} | ||
``` | ||
```ts | ||
interface Foo { | ||
bar: string; | ||
} | ||
interface Bar extends Foo { | ||
(): void; | ||
} | ||
``` | ||
## When Not To Use It | ||
If you specifically want to use an interface or type literal with a single call signature for stylistic reasons, you can disable this rule. | ||
## Further Reading | ||
- TSLint: [`callable-types`](https://palantir.github.io/tslint/rules/callable-types/) |
171 changes: 171 additions & 0 deletionspackages/eslint-plugin/lib/rules/prefer-function-type.js
This file contains hidden or 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,171 @@ | ||
/** | ||
* @fileoverview Use function types instead of interfaces with call signatures | ||
* @author Benjamin Lichtman | ||
*/ | ||
'use strict'; | ||
const util = require('../util'); | ||
/** | ||
* @typedef {import("eslint").Rule.RuleModule} RuleModule | ||
* @typedef {import("estree").Node} ESTreeNode | ||
*/ | ||
//------------------------------------------------------------------------------ | ||
// Rule Definition | ||
//------------------------------------------------------------------------------ | ||
/** | ||
* @type {RuleModule} | ||
*/ | ||
module.exports = { | ||
meta: { | ||
docs: { | ||
description: | ||
'Use function types instead of interfaces with call signatures', | ||
category: 'TypeScript', | ||
recommended: false, | ||
extraDescription: [util.tslintRule('prefer-function-type')], | ||
url: util.metaDocsUrl('prefer-function-type') | ||
}, | ||
fixable: 'code', | ||
messages: { | ||
functionTypeOverCallableType: | ||
"{{ type }} has only a call signature - use '{{ sigSuggestion }}' instead." | ||
}, | ||
schema: [], | ||
type: 'suggestion' | ||
}, | ||
create(context) { | ||
const sourceCode = context.getSourceCode(); | ||
//---------------------------------------------------------------------- | ||
// Helpers | ||
//---------------------------------------------------------------------- | ||
/** | ||
* Checks if there is no supertype or if the supertype is 'Function' | ||
* @param {ESTreeNode} node The node being checked | ||
* @returns {boolean} Returns true iff there is no supertype or if the supertype is 'Function' | ||
*/ | ||
function noSupertype(node) { | ||
if (!node.extends || node.extends.length === 0) { | ||
return true; | ||
} | ||
if (node.extends.length !== 1) { | ||
return false; | ||
} | ||
const expr = node.extends[0].expression; | ||
return expr.type === 'Identifier' && expr.name === 'Function'; | ||
} | ||
/** | ||
* @param {ESTreeNode} parent The parent of the call signature causing the diagnostic | ||
* @returns {boolean} true iff the parent node needs to be wrapped for readability | ||
*/ | ||
function shouldWrapSuggestion(parent) { | ||
switch (parent.type) { | ||
case 'TSUnionType': | ||
case 'TSIntersectionType': | ||
case 'TSArrayType': | ||
return true; | ||
default: | ||
return false; | ||
} | ||
} | ||
/** | ||
* @param {ESTreeNode} call The call signature causing the diagnostic | ||
* @param {ESTreeNode} parent The parent of the call | ||
* @returns {string} The suggestion to report | ||
*/ | ||
function renderSuggestion(call, parent) { | ||
const start = call.range[0]; | ||
const colonPos = call.returnType.range[0] - start; | ||
const text = sourceCode.getText().slice(start, call.range[1]); | ||
let suggestion = `${text.slice(0, colonPos)} =>${text.slice( | ||
colonPos + 1 | ||
)}`; | ||
if (shouldWrapSuggestion(parent.parent)) { | ||
suggestion = `(${suggestion})`; | ||
} | ||
if (parent.type === 'TSInterfaceDeclaration') { | ||
if (typeof parent.typeParameters !== 'undefined') { | ||
return `type ${sourceCode | ||
.getText() | ||
.slice( | ||
parent.id.range[0], | ||
parent.typeParameters.range[1] | ||
)} = ${suggestion}`; | ||
} | ||
return `type ${parent.id.name} = ${suggestion}`; | ||
} | ||
return suggestion.endsWith(';') ? suggestion.slice(0, -1) : suggestion; | ||
} | ||
/** | ||
* @param {ESTreeNode} member The TypeElement being checked | ||
* @param {ESTreeNode} node The parent of member being checked | ||
* @returns {void} | ||
*/ | ||
function checkMember(member, node) { | ||
if ( | ||
(member.type === 'TSCallSignatureDeclaration' || | ||
member.type === 'TSConstructSignatureDeclaration') && | ||
typeof member.returnType !== 'undefined' | ||
) { | ||
const suggestion = renderSuggestion(member, node); | ||
const fixStart = | ||
node.type === 'TSTypeLiteral' | ||
? node.range[0] | ||
: sourceCode | ||
.getTokens(node) | ||
.filter( | ||
token => | ||
token.type === 'Keyword' && token.value === 'interface' | ||
)[0].range[0]; | ||
context.report({ | ||
node: member, | ||
messageId: 'functionTypeOverCallableType', | ||
data: { | ||
type: node.type === 'TSTypeLiteral' ? 'Type literal' : 'Interface', | ||
sigSuggestion: suggestion | ||
}, | ||
fix(fixer) { | ||
return fixer.replaceTextRange( | ||
[fixStart, node.range[1]], | ||
suggestion | ||
); | ||
} | ||
}); | ||
} | ||
} | ||
//---------------------------------------------------------------------- | ||
// Public | ||
//---------------------------------------------------------------------- | ||
return { | ||
/** | ||
* @param {TSInterfaceDeclaration} node The node being checked | ||
* @returns {void} | ||
*/ | ||
TSInterfaceDeclaration(node) { | ||
if (noSupertype(node) && node.body.body.length === 1) { | ||
checkMember(node.body.body[0], node); | ||
} | ||
}, | ||
/** | ||
* @param {TSTypeLiteral} node The node being checked | ||
* @returns {void} | ||
*/ | ||
'TSTypeLiteral[members.length = 1]'(node) { | ||
checkMember(node.members[0], node); | ||
} | ||
}; | ||
} | ||
}; |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
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.