There seems to be an issue with TSlint and its disapproval of using the traditional for(i=0; ...)
loop.
Consider this straightforward code snippet:
this.filters['1','2','3'....];
for (let i = 0; i < this.filters.length; i++) {
if (this.filters[i] === '2') {
this.filters = new_value;
}
}
TSlint suggests converting it to for-of, but that doesn't support modification. An alternative like:
for (const [i, el] of this.filters.entries()) {
triggers a TypeScript compilation warning: Type 'IterableIterator<T>'
is not an array type. Using keys()
feels redundant here.
Why does TSlint persist in complaining about this restriction on for(const i=0; ...)
?
If we execute a similar block of code using for-of:
this.filters['1','2','3'....];
for (let f of this.filters) {
if (f === '2') {
f = new_value;
}
}
We'll notice that the array remains unaltered post-loop. However, things change when the context involves objects:
let filters = [{id:'1'},{id:'2'},{id:'3'}];
console.log(filters)
for (let f of filters) {
if (f.id === '2') {
f.id = 'toto';
}
}
console.log(filters)
Strangely enough, the object array gets modified after the loop! Any insights on why this happens would be appreciated.
I've tried looking for solutions to this problem, referencing a closed GitHub issue at https://github.com/palantir/tslint/pull/1813, but couldn't find a definitive resolution.