diff --git a/packages/eslint-plugin/src/rules/init-declarations.ts b/packages/eslint-plugin/src/rules/init-declarations.ts index 611687b0e9f..a10035c0691 100644 --- a/packages/eslint-plugin/src/rules/init-declarations.ts +++ b/packages/eslint-plugin/src/rules/init-declarations.ts @@ -35,11 +35,7 @@ export default createRule({ if (node.declare) { return; } - if ( - node.parent?.type === AST_NODE_TYPES.TSModuleBlock && - node.parent.parent?.type === AST_NODE_TYPES.TSModuleDeclaration && - node.parent.parent?.declare - ) { + if (isAncestorNamespaceDeclared(node)) { return; } } @@ -47,5 +43,24 @@ export default createRule({ rules['VariableDeclaration:exit'](node); }, }; + + function isAncestorNamespaceDeclared( + node: TSESTree.VariableDeclaration, + ): boolean { + let ancestor = node.parent; + + while (ancestor) { + if ( + ancestor.type === AST_NODE_TYPES.TSModuleDeclaration && + ancestor.declare + ) { + return true; + } + + ancestor = ancestor.parent; + } + + return false; + } }, }); diff --git a/packages/eslint-plugin/tests/rules/init-declarations.test.ts b/packages/eslint-plugin/tests/rules/init-declarations.test.ts index 95d9a08799a..29e9025f734 100644 --- a/packages/eslint-plugin/tests/rules/init-declarations.test.ts +++ b/packages/eslint-plugin/tests/rules/init-declarations.test.ts @@ -341,6 +341,35 @@ namespace myLib { `, options: ['always'], }, + { + code: ` +declare namespace myLib1 { + const foo: number; + namespace myLib2 { + let bar: string; + namespace myLib3 { + let baz: object; + } + } +} + `, + options: ['always'], + }, + + { + code: ` +declare namespace myLib1 { + const foo: number; + namespace myLib2 { + let bar: string; + namespace myLib3 { + let baz: object; + } + } +} + `, + options: ['never'], + }, ], invalid: [ // checking compatibility with base rule @@ -724,5 +753,36 @@ namespace myLib { }, ], }, + { + code: ` +namespace myLib1 { + const foo: number; + namespace myLib2 { + let bar: string; + namespace myLib3 { + let baz: object; + } + } +} + `, + options: ['always'], + errors: [ + { + messageId: 'initialized', + data: { idName: 'foo' }, + type: AST_NODE_TYPES.VariableDeclarator, + }, + { + messageId: 'initialized', + data: { idName: 'bar' }, + type: AST_NODE_TYPES.VariableDeclarator, + }, + { + messageId: 'initialized', + data: { idName: 'baz' }, + type: AST_NODE_TYPES.VariableDeclarator, + }, + ], + }, ], });