Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 43 additions & 6 deletions packages/eslint-plugin/src/rules/no-shadow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
} from '@typescript-eslint/scope-manager';
import * as util from '../util';

type MessageIds = 'noShadow';
type MessageIds = 'noShadow' | 'noShadowGlobal';
type Options = [
{
allow?: string[];
Expand Down Expand Up @@ -64,7 +64,9 @@ export default util.createRule<Options, MessageIds>({
},
],
messages: {
noShadow: "'{{name}}' is already declared in the upper scope.",
noShadow:
"'{{name}}' is already declared in the upper scope on line {{shadowedLine}} column {{shadowedColumn}}.",
noShadowGlobal: "'{{name}}' is already a global variable.",
},
},
defaultOptions: [
Expand Down Expand Up @@ -517,6 +519,28 @@ export default util.createRule<Options, MessageIds>({
);
}

/**
* Get declared line and column of a variable.
* @param variable The variable to get.
* @returns The declared line and column of the variable.
*/
function getDeclaredLocation(
variable: TSESLint.Scope.Variable,
): { global: true } | { global: false; line: number; column: number } {
const identifier = variable.identifiers[0];
if (identifier) {
return {
global: false,
line: identifier.loc.start.line,
column: identifier.loc.start.column + 1,
};
} else {
return {
global: true,
};
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitty nit: could be simplified to return identifier ? { ... } : { ... };.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you really do love your ternaries 😄
personally I prefer to only use ternaries for when I want an expression.
I find in this case where I can do everything with statements - using an if statement is clearer and cleaner.

}

/**
* Checks the current context for shadowed variables.
* @param {Scope} scope Fixme
Expand Down Expand Up @@ -595,12 +619,25 @@ export default util.createRule<Options, MessageIds>({
) &&
!(options.hoist !== 'all' && isInTdz(variable, shadowed))
) {
const location = getDeclaredLocation(shadowed);

context.report({
node: variable.identifiers[0],
messageId: 'noShadow',
data: {
name: variable.name,
},
...(location.global
? {
messageId: 'noShadowGlobal',
data: {
name: variable.name,
},
}
: {
messageId: 'noShadow',
data: {
name: variable.name,
shadowedLine: location.line,
shadowedColumn: location.column,
},
}),
});
}
}
Expand Down
Loading