Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Commit

Permalink
Add auto-fix for no-var-keyword (#1547)
Browse files Browse the repository at this point in the history
Note, we just replace with `let` which can cause errors if the identifier is referenced before the declaration or outside the scope. TypeScript will catch these at type-check time.
  • Loading branch information
alexeagle authored and adidahiya committed Oct 7, 2016
1 parent b5ef1b4 commit 46d48c8
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/rules/noVarKeywordRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ class NoVarKeywordWalker extends Lint.RuleWalker {
public visitVariableStatement(node: ts.VariableStatement) {
if (!Lint.hasModifier(node.modifiers, ts.SyntaxKind.DeclareKeyword)
&& !Lint.isBlockScopedVariable(node)) {
this.addFailure(this.createFailure(node.declarationList.getStart(), "var".length, Rule.FAILURE_STRING));
this.addFailure(this.createFailure(node.declarationList.getStart(), "var".length, Rule.FAILURE_STRING,
this.fix(node.declarationList)));
}

super.visitVariableStatement(node);
Expand All @@ -68,7 +69,12 @@ class NoVarKeywordWalker extends Lint.RuleWalker {
private handleInitializerNode(node: ts.VariableDeclarationList | ts.Expression) {
if (node && node.kind === ts.SyntaxKind.VariableDeclarationList &&
!(Lint.isNodeFlagSet(node, ts.NodeFlags.Let) || Lint.isNodeFlagSet(node, ts.NodeFlags.Const))) {
this.addFailure(this.createFailure(node.getStart(), "var".length, Rule.FAILURE_STRING));
this.addFailure(this.createFailure(node.getStart(), "var".length, Rule.FAILURE_STRING, this.fix(node)));
}
}

private fix = (node: ts.Node) => new Lint.Fix(Rule.metadata.ruleName, [
this.deleteText(node.getStart(), "var".length),
this.appendText(node.getStart(), "let"),
]);
}
44 changes: 44 additions & 0 deletions test/rules/no-var-keyword/test.ts.fix
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
let foo;

function tmp(t: any) {
let x = 3;
}

let i,
j;

let [a, b] = [1, 2];

for (let n; false;);
for (let n1 in foo);
for (let n2 of foo);

export let exportVar0 = 0;
export let exportVar1 = 1;
export let exportVar2 = 2,
exportVar21 = 21;
export /* var tst */ let exportVar3 = 3;

module quz {
export let i;
}

declare var tmp2: any;

let bar;
const qux;

let k,
l;

let [x, y] = [1, 2];

for (n; false;);
for (let n; false;);
for (let name in foo);
for (let name of foo);
for (const name in foo);
for (const name of foo);

export let exportLet = 1;
export const exportConst = 1;

0 comments on commit 46d48c8

Please sign in to comment.