Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [no-use-before-define] allow class references if they're within a class decorator #2827

Merged
merged 1 commit into from Nov 29, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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