Skip to content

Commit e89c5ba

Browse files
committed
fix(typescript/prefer-namespace-keyword): skip nested TSModuleDeclarations (#15806)
Prevent fix replacing text within the module name or block in the case of nested modules. Before this PR: Input: ```ts module X.Y.module { x = "module"; } ``` After fix: ```ts namespace X.Y.namespace { x = "namespace"; } ``` Prevent this by exiting early if the `TSModuleDeclaration` is nested (i.e. `Y` or `module` in above example). Note: I discovered this bug when I replaced early `return` with `unwrap` in #15805. IMO it's better to `unwrap` when you believe the check cannot fail, as the panic may alert us to bugs which may otherwise lie undiscovered. Side note: The design we have with nested `TSModuleDeclaration`s representing `module X.Y.Z {}` is pretty unintutive. I'd like to change it if we can.
1 parent 220d01e commit e89c5ba

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

crates/oxc_linter/src/rules/typescript/prefer_namespace_keyword.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,12 @@ impl Rule for PreferNamespaceKeyword {
6161
return;
6262
}
6363

64+
// Ignore nested `TSModuleDeclaration`s
65+
// e.g. the 2 inner `TSModuleDeclaration`s in `module A.B.C {}`
66+
if let AstKind::TSModuleDeclaration(_) = ctx.nodes().parent_kind(node.id()) {
67+
return;
68+
}
69+
6470
let Some(offset) = ctx.find_next_token_from(module.span.start, "module") else { return };
6571

6672
ctx.diagnostic_with_fix(prefer_namespace_keyword_diagnostic(module.span), |fixer| {
@@ -133,6 +139,11 @@ fn test() {
133139
None,
134140
),
135141
("declare /* module */ module foo {}", "declare /* module */ namespace foo {}", None),
142+
(
143+
"declare module X.Y.module { x = 'module'; }",
144+
"declare namespace X.Y.module { x = 'module'; }",
145+
None,
146+
),
136147
];
137148

138149
Tester::new(PreferNamespaceKeyword::NAME, PreferNamespaceKeyword::PLUGIN, pass, fail)

0 commit comments

Comments
 (0)