Skip to content

Commit

Permalink
fix(eslint-plugin): [no-use-before-define] allow class references if …
Browse files Browse the repository at this point in the history
…they're within a class decorator (#2827)

Fixes #2842
  • Loading branch information
bradzacher committed Nov 29, 2020
1 parent bf904ec commit 050023a
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .cspell.json
Expand Up @@ -89,9 +89,10 @@
"rulesets",
"serializers",
"superset",
"transpiling",
"thenables",
"transpiled",
"transpiles",
"transpiling",
"tsconfigs",
"tsutils",
"typedef",
Expand Down
32 changes: 32 additions & 0 deletions packages/eslint-plugin/src/rules/no-use-before-define.ts
Expand Up @@ -133,6 +133,37 @@ function isInRange(
return !!node && node.range[0] <= location && location <= node.range[1];
}

/**
* Decorators are transpiled such that the decorator is placed after the class declaration
* So it is considered safe
*/
function isClassRefInClassDecorator(
variable: TSESLint.Scope.Variable,
reference: TSESLint.Scope.Reference,
): boolean {
if (variable.defs[0].type !== 'ClassName') {
return false;
}

if (
!variable.defs[0].node.decorators ||
variable.defs[0].node.decorators.length === 0
) {
return false;
}

for (const deco of variable.defs[0].node.decorators) {
if (
reference.identifier.range[0] >= deco.range[0] &&
reference.identifier.range[1] <= deco.range[1]
) {
return true;
}
}

return false;
}

/**
* Checks whether or not a given reference is inside of the initializers of a given variable.
*
Expand Down Expand Up @@ -292,6 +323,7 @@ export default util.createRule<Options, MessageIds>({
(variable.identifiers[0].range[1] <= reference.identifier.range[1] &&
!isInInitializer(variable, reference)) ||
!isForbidden(variable, reference) ||
isClassRefInClassDecorator(variable, reference) ||
reference.from.type === TSESLint.Scope.ScopeType.functionType
) {
return;
Expand Down
34 changes: 34 additions & 0 deletions packages/eslint-plugin/tests/rules/no-use-before-define.test.ts
Expand Up @@ -394,6 +394,40 @@ declare global {
}
}
`,
// https://github.com/typescript-eslint/typescript-eslint/issues/2824
`
@Directive({
selector: '[rcCidrIpPattern]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: CidrIpPatternDirective,
multi: true,
},
],
})
export class CidrIpPatternDirective implements Validator {}
`,
{
code: `
@Directive({
selector: '[rcCidrIpPattern]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: CidrIpPatternDirective,
multi: true,
},
],
})
export class CidrIpPatternDirective implements Validator {}
`,
options: [
{
classes: false,
},
],
},
],
invalid: [
{
Expand Down

0 comments on commit 050023a

Please sign in to comment.