Typescript shadowed variable

Viewed 19642

I'm using TSLint in a TypeScript project and it's complaining about the variable i in the following code:

    for (let i = 0; i < body.children.length; i++)
    {
        body.children[i].classList.remove('active');
    }

The message is 'Shadowed variable: 'i' (no-shadowed-variable)'

Is there anything wrong with this loop and what would be the correct way of doing a for loop in TS?

1 Answers

Shadowing means declaring an identifier that has already been declared in an outer scope. Since this is a linter error, it's not incorrect per se, but it might lead to confusion, as well as make the outer i unavailable inside the loop (where it is being shadowed by the loop variable.)

You can rename either of the i variables, but if you add the rule "prefer-for-of": true to your tslint.json, TSLint will suggest an elegant solution in this case:

for (const child of body.children) {
    child.classList.remove('active');
}

(provided child hasn't been declared already :-)

Related