Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript shadowed variable [duplicate]

Tags:

typescript

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?

like image 784
rbasniak Avatar asked Sep 24 '17 18:09

rbasniak


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 :-)

like image 170
Oblosys Avatar answered Nov 13 '22 06:11

Oblosys