Skip to content

Commit e32bbf6

Browse files
committed
fix(linter/no-var): handle TypeScript declare keyword in fixer (#15426)
Related #14833
1 parent 075079c commit e32bbf6

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

crates/oxc_linter/src/rules/eslint/no_var.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,9 @@ impl Rule for NoVar {
5858
&& dec.kind == VariableDeclarationKind::Var
5959
{
6060
let is_written_to = dec.declarations.iter().any(|v| is_written_to(&v.id, ctx));
61-
let span = Span::sized(dec.span.start, 3);
61+
let var_offset = ctx.find_next_token_from(dec.span.start, "var").unwrap();
62+
let var_start = dec.span.start + var_offset;
63+
let span = Span::sized(var_start, 3);
6264
ctx.diagnostic_with_fix(no_var_diagnostic(span), |fixer| {
6365
let parent_span = ctx.nodes().parent_kind(node.id()).span();
6466
if dec.declarations.iter().any(|decl| {
@@ -74,7 +76,10 @@ impl Rule for NoVar {
7476

7577
fixer.replace(
7678
span,
77-
if is_written_to || !dec.declarations.iter().all(|v| v.init.is_some()) {
79+
if dec.declare
80+
|| is_written_to
81+
|| !dec.declarations.iter().all(|v| v.init.is_some())
82+
{
7883
"let"
7984
} else {
8085
"const"
@@ -181,6 +186,7 @@ fn test() {
181186
"function play(index: number) { if (index > 1) { var a = undefined } else { var a = undefined } console.log(a) }",
182187
"function play(index: number) { if (index > 1) { var a = undefined } else { var a = undefined } console.log(a) }",
183188
),
189+
("declare var foo = 2;", "declare let foo = 2;"),
184190
];
185191

186192
Tester::new(NoVar::NAME, NoVar::PLUGIN, pass, fail).expect_fix(fix).test_and_snapshot();

crates/oxc_linter/src/snapshots/eslint_no_var.snap

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -240,9 +240,9 @@ source: crates/oxc_linter/src/tester.rs
240240
help: Replace var with let or const
241241

242242
eslint(no-var): Unexpected var, use let or const instead.
243-
╭─[no_var.tsx:1:1]
243+
╭─[no_var.tsx:1:9]
244244
1declare var foo = 2;
245-
· ───
245+
· ───
246246
╰────
247247
help: Replace var with let or const
248248

0 commit comments

Comments
 (0)