Home > Blockchain >  Typescript: how to prevent nested arguments of same name
Typescript: how to prevent nested arguments of same name

Time:01-19

I often use generic names for arguments in callbacks. For example, I might readily write:

someArray.forEach((el, ind) => {
    // ...
});

... where el and ind stand for element and index. The problem comes in when I have a lot of nested callbacks, and so I have to start labelling arguments like el1, etc., and my code can get confusing, and it can be tricky to unentangle all of my original el variables.

Is there a way to get typescript to prevent me from reusing the same name in a nested argument? I.e. I want to prevent e.g.:

someArray.forEach((el, ind) => {
    el.forEach(el => {
        // I want the second el to get flagged! 
    })
});

CodePudding user response:

That's perfectly valid Typescript and no compiler flags are provided to prevent shadowing out of the box. So your looking for a tool like eslint to catch softer code quality items like this.

Luckily, eslint has a built in rule for this called no-shadow.

  • Related