Skip to content
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

fix(eslint-plugin): [prefer-function-type] generate correct code in union and intersection #3002

Merged
merged 1 commit into from Feb 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 8 additions & 3 deletions packages/eslint-plugin/src/rules/prefer-function-type.ts
Expand Up @@ -88,6 +88,10 @@ export default util.createRule({
colonPos + 1,
)}`;

const lastChar = suggestion.endsWith(';') ? ';' : '';
if (lastChar) {
suggestion = suggestion.slice(0, -1);
}
if (shouldWrapSuggestion(parent.parent)) {
suggestion = `(${suggestion})`;
}
Expand All @@ -98,16 +102,17 @@ export default util.createRule({
.slice(
parent.id.range[0],
parent.typeParameters.range[1],
)} = ${suggestion}`;
)} = ${suggestion}${lastChar}`;
}
return `type ${parent.id.name} = ${suggestion}`;
return `type ${parent.id.name} = ${suggestion}${lastChar}`;
}
return suggestion.endsWith(';') ? suggestion.slice(0, -1) : suggestion;
return suggestion;
}

/**
* @param member The TypeElement being checked
* @param node The parent of member being checked
* @param tsThisTypes
*/
function checkMember(
member: TSESTree.TypeElement,
Expand Down
34 changes: 34 additions & 0 deletions packages/eslint-plugin/tests/rules/prefer-function-type.test.ts
Expand Up @@ -268,5 +268,39 @@ type Foo = () => {
};
`,
},
{
code: noFormat`
type X = {} | { (): void; }
`,
errors: [
{
messageId: 'functionTypeOverCallableType',
type: AST_NODE_TYPES.TSCallSignatureDeclaration,
data: {
literalOrInterface: phrases[AST_NODE_TYPES.TSTypeLiteral],
},
},
],
output: noFormat`
type X = {} | (() => void)
`,
},
{
code: noFormat`
type X = {} & { (): void; };
`,
errors: [
{
messageId: 'functionTypeOverCallableType',
type: AST_NODE_TYPES.TSCallSignatureDeclaration,
data: {
literalOrInterface: phrases[AST_NODE_TYPES.TSTypeLiteral],
},
},
],
output: noFormat`
type X = {} & (() => void);
`,
},
],
});