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): [no-unnecessary-type-constraint] correctly fix in cts/mts files #6795

Merged
23 changes: 21 additions & 2 deletions packages/eslint-plugin/src/rules/no-unnecessary-type-constraint.ts
@@ -1,3 +1,5 @@
import { extname } from 'node:path';
armano2 marked this conversation as resolved.
Show resolved Hide resolved

import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import * as semver from 'semver';
Expand Down Expand Up @@ -60,7 +62,24 @@ export default util.createRule({
])
: new Map([[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 @@ -69,7 +88,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 @@ -123,6 +123,46 @@ function data<T extends TODO>() {}
],
filename: 'react.tsx',
},
{
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