Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [init-declarations] fix nested namespace #4544

Merged
merged 2 commits into from Feb 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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,
},
],
},
],
});