Skip to content

Commit

Permalink
fix(eslint-plugin): [no-unnecessary-type-constraint] correctly fix in…
Browse files Browse the repository at this point in the history
… cts/mts files (#6795)

Co-authored-by: Brad Zacher <brad.zacher@gmail.com>
  • Loading branch information
WoodyWoodsta and bradzacher committed Jul 17, 2023
1 parent d67fd6d commit 1404796
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
23 changes: 21 additions & 2 deletions packages/eslint-plugin/src/rules/no-unnecessary-type-constraint.ts
@@ -1,5 +1,7 @@
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import { extname } from 'path';
import * as ts from 'typescript';

import * as util from '../util';

Expand Down Expand Up @@ -38,7 +40,24 @@ export default util.createRule({
[AST_NODE_TYPES.TSUnknownKeyword, 'unknown'],
]);

const inJsx = context.getFilename().toLowerCase().endsWith('tsx');
function checkRequiresGenericDeclarationDisambiguation(
filename: string,
): boolean {
const pathExt = extname(filename).toLocaleLowerCase();
switch (pathExt) {
case ts.Extension.Cts:
case ts.Extension.Mts:
case ts.Extension.Tsx:
return true;

default:
return false;
}
}

const requiresGenericDeclarationDisambiguation =
checkRequiresGenericDeclarationDisambiguation(context.getFilename());

const source = context.getSourceCode();

const checkNode = (
Expand All @@ -47,7 +66,7 @@ export default util.createRule({
): void => {
const constraint = unnecessaryConstraints.get(node.constraint.type);
function shouldAddTrailingComma(): boolean {
if (!inArrowFunction || !inJsx) {
if (!inArrowFunction || !requiresGenericDeclarationDisambiguation) {
return false;
}
// Only <T>() => {} would need trailing comma
Expand Down
Expand Up @@ -128,6 +128,46 @@ function data<T extends TODO>() {}
},
},
},
{
code: 'const data = <T extends any>() => {};',
errors: [
{
data: { constraint: 'any', name: 'T' },
messageId: 'unnecessaryConstraint',
endColumn: 28,
column: 15,
line: 1,
suggestions: [
{
messageId: 'removeUnnecessaryConstraint',
data: { constraint: 'any' },
output: `const data = <T,>() => {};`,
},
],
},
],
filename: 'file.mts',
},
{
code: 'const data = <T extends any>() => {};',
errors: [
{
data: { constraint: 'any', name: 'T' },
messageId: 'unnecessaryConstraint',
endColumn: 28,
column: 15,
line: 1,
suggestions: [
{
messageId: 'removeUnnecessaryConstraint',
data: { constraint: 'any' },
output: `const data = <T,>() => {};`,
},
],
},
],
filename: 'file.cts',
},
{
code: noFormat`const data = <T extends any,>() => {};`,
errors: [
Expand Down

0 comments on commit 1404796

Please sign in to comment.