Search code examples
typescripttslint

no-unused-vars error despite while loop using variable


In this example a function declares a variable, inComingColor and that variable is then used in a subsequent while loop.

priority(to: Position, cols: Color[][]) {
    let index = to.index + 1; 
    let colorMatchCount = 0;
    let inComingColor = cols[to.col][to.index]; // no-unused-vars error

    while(index < 4) {
        if(inComingColor = cols[to.col][index]) {    // variable used here
            colorMatchCount++;
            index++;
        } else return 0;
    }
    return colorMatchCount;
}

However, a tslint error appears next to the instantiation of this variable:

'inComingColor' is assigned a value but never used
@typescript-eslint/no-unused-vars

My guess is that the linter is making this complaint because it might be possible for an index greater than 3 to occur. Then the while loop will never execute and inComingColor will never be used. (This wont actually happen because the length of these Color[] types is capped at 4).

Anyway, without having to disable the error in-line, is there a tidy way to refactor this function so that the error will disappear?

EDIT: it looks like the linter was just issuing an unhelpful error. I had a mistake. The if statement should not have been using the assignment operator:

if(inComingColor === cols[to.col][index]) {   // correct: error disappears

Solution

  • You will need to assign it before the if check:

            inComingColor = cols[to.col][index];
            if(inComingColor) {    // variable used here
    

    Or just check the value you are assigning it to instead:

            if(cols[to.col][index]) {