unional unional - 10 days ago 7
TypeScript Question

Get around tslint: one-variable-per-declaration

How to code under this rule for the following?

let someArray = [...];
for (let i = 0, n = someArray.length; i < n; i++) {
...
}

Answer

This is practically a classic in JavaScript.

The tsLint rule is designed to favour readability in your code.

Most people cache the length of the array because they perceive there to be a performance benefit. If this is the only reason you are doing it, the potential marginal gain is not worth the readability cost (and it was in fact slower when I ran the JSPerf test in my browser).

So this is the default "tsLint recommended solution"...

for (let i = 0; i < someArray.length; i++) {

In JavaScript, the length property doesn't iterate the array, so the cost is negligible.

If you disagree, you can of course disable the rule - here is the "comment" way to do that.

/* tslint:disable:one-variable-per-declaration */

Or the config way:

"one-variable-per-declaration": false

Or in your case, you may want to use the config flag that disables it just for for loops:

"one-variable-per-declaration": [true, "ignore-for-loop"]
Comments