[tslint]Expected a 'for-of' loop instead of a 'for' loop with this simple iteration (prefer-for-of)
Asked Answered
W

2

72

I have got a tslint error to my for loop when I try to resolve it it says to convert to for-of. I have seen many docs but its not helpful.How can I solve the lint error and I cannot do tslint:disable-next-line:prefer-for-of

for (let i = 0; i < this.rows.length; ++i) {
    if (!this.rows[i].selected) {
        this.selectAllChecked = false;
        break;
    }
}
Warn answered 12/3, 2018 at 19:25 Comment(0)
S
127

It is asking you to use format like the following. The of keyword loops over the objects in the array instead of looping over the indexes of the array. I'm assuming it is triggering because you are only using the index as a way of getting to the value in the array (which can be cleaned up using the of syntax).

for (let row of this.rows) {
    if (!row.selected) {
        this.selectAllChecked = false;
        break;
    }
}

As a note, you can accomplish the same thing using the following one-liner:

this.selectAllChecked = this.rows.every(row => row.selected);
Seibel answered 12/3, 2018 at 20:47 Comment(6)
i get this error with a FileList, is it a false positive? Because i can't use for..of with filelistsHoulihan
@Houlihan at the moment I believe it is a false positive as FileList is not yet an iterable object (although it looks like they are planning on changing that based on the note in the spec: w3.org/TR/FileAPI/#filelist-section)Seibel
Any suggestions how to iterate over a FileList without hitting lint and beeing future-proof at the same time?Houlihan
@Houlihan there has been an issue for this exact thing opened for a while (github.com/palantir/tslint/issues/2021). It looks like TSLint is being deprecated in favor of ESLint, so the long term strategy to fix this would be to transform to using that. In the short term you can just disabled that rule for these lines using the comment syntax.Seibel
But what if you want to have the index of the item its easier to have first syntaxWillodeanwilloughby
How can you do that in a HTMLCollectionOf ?Zarger
T
8

In tslint.json we can add inside the rules:

"rules": {
    "prefer-for-of": false
}

This will resolve the issue by disabling the relevant lint rule.

Tifanie answered 7/10, 2021 at 7:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.