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 c1b86bf8c61f..5f8fe91cba3e 100644 --- a/packages/eslint-plugin/src/rules/consistent-indexed-object-style.ts +++ b/packages/eslint-plugin/src/rules/consistent-indexed-object-style.ts @@ -95,12 +95,46 @@ export default createRule({ return; } + const scope = context.getScope(); + if ( + scope.block.type == AST_NODE_TYPES.Program && + scope.block.body[0].type == AST_NODE_TYPES.TSTypeAliasDeclaration + ) { + const body = scope.block.body[0]; + const name = body?.id.name; + const memberTypes = member.typeAnnotation?.typeAnnotation; + if (memberTypes) { + if ( + memberTypes.type == AST_NODE_TYPES.TSTypeReference && + memberTypes.typeName.type == AST_NODE_TYPES.Identifier && + memberTypes.typeName.name == name + ) { + return; + } else if (memberTypes.type == AST_NODE_TYPES.TSUnionType) { + const membersArray = memberTypes.types; + let flag = false; + membersArray.forEach((m: TSESTree.Node) => { + if ( + m.type == AST_NODE_TYPES.TSTypeReference && + m.typeName.type == AST_NODE_TYPES.Identifier && + m.typeName.name == name + ) { + flag = true; + } + }); + if (flag) { + return; + } + } + } + } + context.report({ node, messageId: 'preferRecord', fix(fixer) { - const key = sourceCode.getText(keyType.typeAnnotation); const value = sourceCode.getText(valueType.typeAnnotation); + const key = sourceCode.getText(keyType.typeAnnotation); return fixer.replaceText( node, `${prefix}Record<${key}, ${value}>${postfix}`, 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 ebedccf424a7..ada62733c29e 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 @@ -76,6 +76,8 @@ interface Foo { []; } `, + 'type Foo = { [key: string]: string | Foo };', + 'type Foo = { [key: string]: Foo };', // 'index-signature' // Unhandled type @@ -172,6 +174,26 @@ type Foo = Record; output: 'type Foo = Record;', errors: [{ messageId: 'preferRecord', line: 1, column: 12 }], }, + { + code: 'type T = { [k: string]: AT };', + output: 'type T = Record;', + errors: [{ messageId: 'preferRecord', line: 1, column: 10 }], + }, + { + code: 'type T = { [k: string]: TA };', + output: 'type T = Record;', + errors: [{ messageId: 'preferRecord', line: 1, column: 10 }], + }, + { + code: 'type T = { [k: string]: A.T };', + output: 'type T = Record;', + errors: [{ messageId: 'preferRecord', line: 1, column: 10 }], + }, + { + code: 'type Foo = { [key: string]: AnotherFoo };', + output: 'type Foo = Record;', + errors: [{ messageId: 'preferRecord', line: 1, column: 12 }], + }, // Generic {