From 73d97130afe79b8a458c215581ce86c62009ad8b Mon Sep 17 00:00:00 2001 From: Timo Zander Date: Sun, 1 Nov 2020 20:25:48 +0100 Subject: [PATCH] fix(eslint-plugin): [consistent-indexed-object-style] fix wrong autofix behaviour with generics (#2722) --- .../rules/consistent-indexed-object-style.ts | 15 +++++++- .../consistent-indexed-object-style.test.ts | 34 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/packages/eslint-plugin/src/rules/consistent-indexed-object-style.ts b/packages/eslint-plugin/src/rules/consistent-indexed-object-style.ts index 021f5038770..c1b86bf8c61 100644 --- a/packages/eslint-plugin/src/rules/consistent-indexed-object-style.ts +++ b/packages/eslint-plugin/src/rules/consistent-indexed-object-style.ts @@ -115,7 +115,20 @@ export default createRule({ }, TSInterfaceDeclaration(node): void { - checkMembers(node.body.body, node, `type ${node.id.name} = `, ';'); + let genericTypes = ''; + + if ((node.typeParameters?.params ?? []).length > 0) { + genericTypes = `<${node.typeParameters?.params + .map(p => p.name.name) + .join(', ')}>`; + } + + checkMembers( + node.body.body, + node, + `type ${node.id.name}${genericTypes} = `, + ';', + ); }, }; }, diff --git a/packages/eslint-plugin/tests/rules/consistent-indexed-object-style.test.ts b/packages/eslint-plugin/tests/rules/consistent-indexed-object-style.test.ts index 328f0cbf5dd..ebedccf424a 100644 --- a/packages/eslint-plugin/tests/rules/consistent-indexed-object-style.test.ts +++ b/packages/eslint-plugin/tests/rules/consistent-indexed-object-style.test.ts @@ -140,6 +140,32 @@ type Foo = Record; errors: [{ messageId: 'preferRecord', line: 2, column: 1 }], }, + // Interface with generic parameter + { + code: ` +interface Foo { + [key: string]: A; +} + `, + output: ` +type Foo = Record; + `, + errors: [{ messageId: 'preferRecord', line: 2, column: 1 }], + }, + + // Interface with multiple generic parameters + { + code: ` +interface Foo { + [key: A]: B; +} + `, + output: ` +type Foo = Record; + `, + errors: [{ messageId: 'preferRecord', line: 2, column: 1 }], + }, + // Type literal { code: 'type Foo = { [key: string]: any };', @@ -175,6 +201,14 @@ type Foo = Record; errors: [{ messageId: 'preferIndexSignature', line: 1, column: 12 }], }, + // Type literal with generic parameter + { + code: 'type Foo = Record;', + options: ['index-signature'], + output: 'type Foo = { [key: string]: T };', + errors: [{ messageId: 'preferIndexSignature', line: 1, column: 15 }], + }, + // Generic { code: 'type Foo = Generic>;',