Tslint: "prefer-const" rule to discourage unnecessary use of "let"

Created on 10 Jul 2015  路  10Comments  路  Source: palantir/tslint

I'd like a new rule that prevents declaring variables as let _unless that reference is later mutated via a left-hand-side assignment_. const should be used instead for better readability if you intend to never re-assign the variable.

Some code examples:

// bad
for (let i of [1, 2, 3]) {
  //
}

// good
for (const i of [1, 2, 3]) {
  //
}

// bad
let {createReadStream} = require("fs");

// good, unless the recently-introduced "no-require-imports" rule is also enabled
const {createReadStream} = require("fs");
P1 Fixed Rule Suggestion

Most helpful comment

@weswigham any news on this?

All 10 comments

:+1:

:+1:

@weswigham has done this for us. I think he'll be able to send out a PR eventually.

@weswigham any news on this?

+1 - eslint has this rule

It appears that the mentioned PR was merged into Microsoft/typescript. Has anyone had this rule working successfully?

It's in tslint-microsoft-contrib and it's working for me (for the most part).

I just got this rule working.

npm install --save-dev tslint-microsoft-contrib

tslint.json:

{
  "extends": ["tslint:recommended"],
  "rules": {
     "prefer-const": true
  },
  "rulesDirectory": [
     "node_modules/tslint-microsoft-contrib"
  ]
}

assigning to @nchen63 to tackle after the 4.0 release. here's a WIP branch I started a while ago... https://github.com/palantir/tslint/tree/wip-prefer-const

Was this page helpful?
0 / 5 - 0 ratings