32

tslint is currently throwing the following error

Shadowed name: 'err'

Here is the code

fs.readdir(fileUrl, (err, files) => {
        fs.readFile(path.join(fileUrl, files[0]), function (err, data) {
            if (!err) {
                res.send(data);
            }
        });
    });

Anybody have a clue on what the best way would be to solve this and what the error even means?

bobdolan
  • 563
  • 3
  • 9
  • 21
  • 9
    It means you've shadowed the name `err`; you're using the same name for the error in two nested callbacks, so the outer error is inaccessible in the inner callback body. As to how to solve it: use a different name for one of them. – jonrsharpe May 28 '18 at 08:28

5 Answers5

40

You are using the same variable "err" in both outer and inner callbacks, which is prevented by tslint.

If you want to use the same variable then "no-shadowed-variable": false, otherwise do as below.

fs.readdir(fileUrl, (readDirError, files) => {
    fs.readFile(path.join(fileUrl, files[0]), function (err, data) {
            if (!err) {
                res.send(data);
            }
        });
    });
5

Add this comment just above the error line--

// tslint:disable-next-line:no-shadowed-variable

Ankit
  • 4,755
  • 2
  • 22
  • 14
3

This shadowed name tslint error is due to repetition of the name 'err' twice in your callback functions. You can change either anyone 'err' to other name so this should work.

Example: This should work

fs.readdir(fileUrl, (error, files) => {
        fs.readFile(path.join(fileUrl, files[0]), function (err, data) {
            if (!err) {
                res.send(data);
            }
        });
    });
3

When same variable is declared multiple times in same scope, this warning occurs.

Use different variable names in such cases.

Yuvraj Patil
  • 7,944
  • 5
  • 56
  • 56
0

this line will disable your error,

// tslint:disable: no-shadowed-variable

but it's not okay to have tow err variables you can also change the second err variable name to something different

fs.readdir(fileUrl, (err, files) => {
  fs.readFile(path.join(fileUrl, files[0]), function (readFileErr, data) {        
    if (!readFileErr) {
            res.send(data);
        }
    });
});

I had an error like this interfaces.ts:119:26 - Shadowed name: 'POST'

// tslint:disable: no-shadowed-variable
interface API {
   export namespace APINAME {
     export type POST {

     }
   }
   export namespace OTHERAPINAME {
     export type POST {

     }
   }
}

I have disabled this error case with this line // tslint:disable: no-shadowed-variable because sometimes typescript compiler cannot understand your code right :)

Nver Abgaryan
  • 621
  • 8
  • 13