Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tslint Error - Shadowed name: 'err'

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?

like image 391
bobdolan Avatar asked May 28 '18 08:05

bobdolan


People also ask

What is shadowed variable Tslint?

When a variable in a local scope and a variable in the containing scope have the same name, shadowing occurs. Shadowing makes it impossible to access the variable in the containing scope and obscures to what value an identifier actually refers to.

What is shadowed name typescript?

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

What is shadowing in Javascript?

In programming, shadowing occurs when a variable declared in a certain scope (e.g. a local variable) has the same name as a variable in an outer scope (e.g. a global variable). When this happens, the outer variable is said to be shadowed by the inner variable.


4 Answers

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);
            }
        });
    });
like image 53
Padmapriya Vishnuvardhan Avatar answered Oct 21 '22 10:10

Padmapriya Vishnuvardhan


Add this comment just above the error line--

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

like image 5
Ankit Avatar answered Oct 21 '22 08:10

Ankit


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);
            }
        });
    });
like image 3
vijaya bharathi Avatar answered Oct 21 '22 08:10

vijaya bharathi


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

Use different variable names in such cases.

like image 3
Yuvraj Patil Avatar answered Oct 21 '22 10:10

Yuvraj Patil