69

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;
    }
}
Daniel W Strimpel
  • 8,190
  • 2
  • 28
  • 38
Juke
  • 1,306
  • 2
  • 11
  • 27

2 Answers2

121

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);
Daniel W Strimpel
  • 8,190
  • 2
  • 28
  • 38
  • 2
    i get this error with a FileList, is it a false positive? Because i can't use for..of with filelists – wutzebaer Jan 17 '20 at 11:21
  • 3
    @wutzebaer 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: https://www.w3.org/TR/FileAPI/#filelist-section) – Daniel W Strimpel Jan 17 '20 at 13:32
  • 1
    Any suggestions how to iterate over a FileList without hitting lint and beeing future-proof at the same time? – wutzebaer Jan 20 '20 at 11:33
  • 3
    @wutzebaer there has been an issue for this exact thing opened for a while (https://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. – Daniel W Strimpel Jan 20 '20 at 14:59
  • But what if you want to have the index of the item its easier to have first syntax – Medin Jan 12 '21 at 15:32
6

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.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Niranjana V S
  • 147
  • 2
  • 3