Search code examples
typescripttslint

Shadow variable in warning in lambda function


I'm using tslint on a Typescript project and I'm often getting warnings about shadow variables in lamdba functions.

Here's an example:

const page = this.currentDocument.pages.find(page => page.pageNumber === pageNumber);

Here the warning is about the page variable.

I've already changed this because I find that's in bad style and confusing to reuse the page variable name here but I'm wondering if this could create a bug or is this just a style/comprehension issue in these cases. I know that shadow variables can often create bugs in other circumstances.

Does someone have an example of what could specifically go wrong here?


Solution

  • Not really no. The only way a shadowed variable is going to cause bugs is if you did not mean to shadow the variable. A very contrived example:

    const factors = [ 1, 2, 3, 4 ]
    const factor = 5
    const factorsMultiplied = factors.map(factor => factor * factor) 
    // [ 1, 4, 9, 16 ] but expected [ 5, 10, 15, 20 ]
    

    As long as you're certain that you don't need to access the variable you've shadowed within the closure you shadowed it then you won't run into any weird behaviors.

    If you want to disable the rule it in certain cases you can do this:

    /*tslint:disable:no-shadowed-variable*/
    const page = this.currentDocument.pages.find(page => page.pageNumber === pageNumber);
    /*tslint:enable:no-shadowed-variable*/