Skip to content

Commit

Permalink
fix(eslint-plugin): [init-declarations] fix nested namespace (#4544)
Browse files Browse the repository at this point in the history
  • Loading branch information
lonyele committed Feb 14, 2022
1 parent 4da9278 commit fe910e6
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 5 deletions.
25 changes: 20 additions & 5 deletions packages/eslint-plugin/src/rules/init-declarations.ts
Expand Up @@ -35,17 +35,32 @@ export default createRule<Options, MessageIds>({
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;
}
}

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;
}
},
});
60 changes: 60 additions & 0 deletions packages/eslint-plugin/tests/rules/init-declarations.test.ts
Expand Up @@ -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
Expand Down Expand Up @@ -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,
},
],
},
],
});

0 comments on commit fe910e6

Please sign in to comment.