Skip to content

Commit

Permalink
feat(eslint-plugin): [no-redeclare] ignoreDeclarationMerge of enum+na…
Browse files Browse the repository at this point in the history
…mespace (#3572)
  • Loading branch information
idan-at committed Jul 31, 2021
1 parent 3ef5267 commit 18e30cb
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/eslint-plugin/docs/rules/no-redeclare.md
Expand Up @@ -41,6 +41,7 @@ When set to `true`, the rule will ignore declaration merges between the followin
- class + namespace
- class + interface + namespace
- function + namespace
- enum + namespace

Examples of **correct** code with `{ ignoreDeclarationMerge: true }`:

Expand Down
27 changes: 26 additions & 1 deletion packages/eslint-plugin/src/rules/no-redeclare.ts
Expand Up @@ -63,6 +63,10 @@ export default util.createRule<Options, MessageIds>({
AST_NODE_TYPES.TSModuleDeclaration,
AST_NODE_TYPES.FunctionDeclaration,
]);
const ENUM_DECLARATION_MERGE_NODES = new Set<AST_NODE_TYPES>([
AST_NODE_TYPES.TSEnumDeclaration,
AST_NODE_TYPES.TSModuleDeclaration,
]);

function* iterateDeclarations(variable: TSESLint.Scope.Variable): Generator<
{
Expand Down Expand Up @@ -164,12 +168,33 @@ export default util.createRule<Options, MessageIds>({
return;
}

// there's more than one class declaration, which needs to be reported
// there's more than one function declaration, which needs to be reported
for (const { identifier } of functionDecls) {
yield { type: 'syntax', node: identifier, loc: identifier.loc };
}
return;
}

if (
// enum + namespace merging
identifiers.every(({ parent }) =>
ENUM_DECLARATION_MERGE_NODES.has(parent.type),
)
) {
const enumDecls = identifiers.filter(
({ parent }) => parent.type === AST_NODE_TYPES.TSEnumDeclaration,
);
if (enumDecls.length === 1) {
// safe declaration merging
return;
}

// there's more than one enum declaration, which needs to be reported
for (const { identifier } of enumDecls) {
yield { type: 'syntax', node: identifier, loc: identifier.loc };
}
return;
}
}

for (const { identifier } of identifiers) {
Expand Down
24 changes: 24 additions & 0 deletions packages/eslint-plugin/tests/rules/no-redeclare.test.ts
Expand Up @@ -122,6 +122,13 @@ namespace A {}
code: `
interface A {}
class A {}
namespace A {}
`,
options: [{ ignoreDeclarationMerge: true }],
},
{
code: `
enum A {}
namespace A {}
`,
options: [{ ignoreDeclarationMerge: true }],
Expand Down Expand Up @@ -605,6 +612,23 @@ class A {}
},
{
code: `
enum A {}
namespace A {}
enum A {}
`,
options: [{ ignoreDeclarationMerge: true }],
errors: [
{
messageId: 'redeclared',
data: {
id: 'A',
},
line: 4,
},
],
},
{
code: `
function A() {}
class A {}
namespace A {}
Expand Down

0 comments on commit 18e30cb

Please sign in to comment.