diff --git a/packages/eslint-plugin/src/rules/consistent-generic-constructors.ts b/packages/eslint-plugin/src/rules/consistent-generic-constructors.ts index 1ccdeab215f..eaceb6131e0 100644 --- a/packages/eslint-plugin/src/rules/consistent-generic-constructors.ts +++ b/packages/eslint-plugin/src/rules/consistent-generic-constructors.ts @@ -65,11 +65,24 @@ export default createRule({ } if (mode === 'rhs' && lhs?.typeParameters && !rhs.typeParameters) { const hasParens = sourceCode.getTokenAfter(rhs.callee)?.value === '('; + const extraComments = new Set( + sourceCode.getCommentsInside(lhs.parent!), + ); + sourceCode + .getCommentsInside(lhs.typeParameters) + .forEach(c => extraComments.delete(c)); context.report({ node, messageId: 'preferRHS', *fix(fixer) { yield fixer.remove(lhs.parent!); + for (const comment of extraComments) { + yield fixer.insertTextAfter( + rhs.callee, + // @ts-expect-error: `sourceCode.getText` should accept `TSESTree.Comment` + sourceCode.getText(comment), + ); + } yield fixer.insertTextAfter( rhs.callee, sourceCode.getText(lhs.typeParameters), diff --git a/packages/eslint-plugin/tests/rules/consistent-generic-constructors.test.ts b/packages/eslint-plugin/tests/rules/consistent-generic-constructors.test.ts index 1a0d260dbee..0d1475e19f4 100644 --- a/packages/eslint-plugin/tests/rules/consistent-generic-constructors.test.ts +++ b/packages/eslint-plugin/tests/rules/consistent-generic-constructors.test.ts @@ -117,14 +117,13 @@ ruleTester.run('consistent-generic-constructors', rule, { output: noFormat`const a = new Foo();`, }, { - code: 'const a: Foo/* comment */ = new Foo();', + code: 'const a: /* comment */ Foo/* another */ = new Foo();', errors: [ { messageId: 'preferRHS', }, ], - // FIXME - output: 'const a = new Foo();', + output: noFormat`const a = new Foo/* comment *//* another */();`, }, { code: 'const a: Foo/* comment */ = new Foo /* another */();', @@ -133,8 +132,7 @@ ruleTester.run('consistent-generic-constructors', rule, { messageId: 'preferRHS', }, ], - // FIXME - output: 'const a = new Foo /* another */();', + output: noFormat`const a = new Foo/* comment */ /* another */();`, }, { code: noFormat`const a: Foo = new \n Foo \n ();`, @@ -205,5 +203,15 @@ ruleTester.run('consistent-generic-constructors', rule, { ], output: noFormat`const a: Foo = new Foo/* comment */ /* another */();`, }, + { + code: 'const a = new Foo();', + options: ['lhs'], + errors: [ + { + messageId: 'preferLHS', + }, + ], + output: noFormat`const a: Foo = new Foo();`, + }, ], });