From e0e68c206f2d614e0c931f79c504026f02d794f2 Mon Sep 17 00:00:00 2001 From: Phillip Huang Date: Wed, 6 Nov 2024 21:15:35 -0800 Subject: [PATCH] fix(eslint-plugin): [consistent-indexed-object-style] handle circular mapped types --- .../rules/consistent-indexed-object-style.ts | 18 ++++++++++++++++++ .../consistent-indexed-object-style.test.ts | 1 + 2 files changed, 19 insertions(+) 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 768bdc84491a..e5ddecdd815f 100644 --- a/packages/eslint-plugin/src/rules/consistent-indexed-object-style.ts +++ b/packages/eslint-plugin/src/rules/consistent-indexed-object-style.ts @@ -176,6 +176,24 @@ export default createRule({ return; } + // If the mapped type is circular, we can't convert it to a Record. + const parentId = findParentDeclaration(node)?.id; + if (parentId) { + const scope = context.sourceCode.getScope(key); + const superVar = ASTUtils.findVariable(scope, parentId.name); + if (superVar) { + const isCircular = superVar.references.some( + item => + item.isTypeReference && + node.range[0] <= item.identifier.range[0] && + node.range[1] >= item.identifier.range[1], + ); + if (isCircular) { + return; + } + } + } + // There's no builtin Mutable type, so we can't autofix it really. const canFix = node.readonly !== '-'; 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 40da904bbac9..e2a1ac63ba13 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 @@ -33,6 +33,7 @@ interface Foo { 'type Foo = { [key: string]: string | Foo };', 'type Foo = { [key: string]: Foo };', 'type Foo = { [key: string]: Foo } | Foo;', + 'type Foo = { [key in string]: Foo };', ` interface Foo { [key: string]: Foo;