From 46d48c8788a747eb35e335df4a90fdb937100e9d Mon Sep 17 00:00:00 2001 From: Alex Eagle Date: Fri, 7 Oct 2016 10:33:18 -0700 Subject: [PATCH] Add auto-fix for no-var-keyword (#1547) 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. --- src/rules/noVarKeywordRule.ts | 10 ++++-- test/rules/no-var-keyword/test.ts.fix | 44 +++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 test/rules/no-var-keyword/test.ts.fix diff --git a/src/rules/noVarKeywordRule.ts b/src/rules/noVarKeywordRule.ts index 6b81c122ae8..2c51ec52756 100644 --- a/src/rules/noVarKeywordRule.ts +++ b/src/rules/noVarKeywordRule.ts @@ -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); @@ -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"), + ]); } diff --git a/test/rules/no-var-keyword/test.ts.fix b/test/rules/no-var-keyword/test.ts.fix new file mode 100644 index 00000000000..a01748fb9da --- /dev/null +++ b/test/rules/no-var-keyword/test.ts.fix @@ -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;