Skip to content

Commit

Permalink
fix(eslint-plugin): [no-namespace] allow namespaces in nested declara…
Browse files Browse the repository at this point in the history
…tions with `allowDeclarations` (#2238)
  • Loading branch information
cherryblossom000 committed Jul 6, 2020
1 parent 16667b1 commit c1df669
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 1 deletion.
8 changes: 8 additions & 0 deletions packages/eslint-plugin/docs/rules/no-namespace.md
Expand Up @@ -51,6 +51,14 @@ Examples of **correct** code for the `{ "allowDeclarations": true }` option:
declare module 'foo' {}
declare module foo {}
declare namespace foo {}

declare global {
namespace foo {}
}

declare module foo {
namespace foo {}
}
```

Examples of **incorrect** code for the `{ "allowDeclarations": false }` option:
Expand Down
10 changes: 9 additions & 1 deletion packages/eslint-plugin/src/rules/no-namespace.ts
Expand Up @@ -50,6 +50,14 @@ export default util.createRule<Options, MessageIds>({
create(context, [{ allowDeclarations, allowDefinitionFiles }]) {
const filename = context.getFilename();

function isDeclaration(node: TSESTree.TSModuleDeclaration): boolean {
return (
node.declare === true ||
(node.parent!.parent?.type === AST_NODE_TYPES.TSModuleDeclaration &&
isDeclaration(node.parent!.parent))
);
}

return {
"TSModuleDeclaration[global!=true][id.type='Identifier']"(
node: TSESTree.TSModuleDeclaration,
Expand All @@ -58,7 +66,7 @@ export default util.createRule<Options, MessageIds>({
(node.parent &&
node.parent.type === AST_NODE_TYPES.TSModuleDeclaration) ||
(allowDefinitionFiles && util.isDefinitionFile(filename)) ||
(allowDeclarations && node.declare === true)
(allowDeclarations && isDeclaration(node))
) {
return;
}
Expand Down
58 changes: 58 additions & 0 deletions packages/eslint-plugin/tests/rules/no-namespace.test.ts
Expand Up @@ -17,6 +17,42 @@ ruleTester.run('no-namespace', rule, {
code: 'declare namespace foo {}',
options: [{ allowDeclarations: true }],
},
{
code: `
declare global {
namespace foo {}
}
`,
options: [{ allowDeclarations: true }],
},
{
code: `
declare module foo {
namespace bar {}
}
`,
options: [{ allowDeclarations: true }],
},
{
code: `
declare global {
namespace foo {
namespace bar {}
}
}
`,
options: [{ allowDeclarations: true }],
},
{
code: `
declare namespace foo {
namespace bar {
namespace baz {}
}
}
`,
options: [{ allowDeclarations: true }],
},
{
filename: 'test.d.ts',
code: 'namespace foo {}',
Expand Down Expand Up @@ -71,6 +107,28 @@ ruleTester.run('no-namespace', rule, {
},
],
},
{
code: 'module foo {}',
options: [{ allowDeclarations: true }],
errors: [
{
messageId: 'moduleSyntaxIsPreferred',
line: 1,
column: 1,
},
],
},
{
code: 'namespace foo {}',
options: [{ allowDeclarations: true }],
errors: [
{
messageId: 'moduleSyntaxIsPreferred',
line: 1,
column: 1,
},
],
},
{
code: 'declare module foo {}',
errors: [
Expand Down

0 comments on commit c1df669

Please sign in to comment.