-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
Copy pathlifecycleHookInterfaceRule.ts
58 lines (52 loc) · 1.78 KB
/
lifecycleHookInterfaceRule.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import ts from 'typescript';
import * as Lint from 'tslint';
const HOOKS_TO_INTERFACES: Record<string, string> = {
'ngOnChanges': 'OnChanges',
'ngOnInit': 'OnInit',
'ngDoCheck': 'DoCheck',
'ngAfterContentInit': 'AfterContentInit',
'ngAfterContentChecked': 'AfterContentChecked',
'ngAfterViewInit': 'AfterViewInit',
'ngAfterViewChecked': 'AfterViewChecked',
'ngOnDestroy': 'OnDestroy',
'ngDoBootstrap': 'DoBootstrap',
};
/**
* Rule that requires classes using Angular lifecycle hooks to implement the appropriate interfaces.
*/
export class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new Walker(sourceFile, this.getOptions()));
}
}
class Walker extends Lint.RuleWalker {
override visitClassDeclaration(node: ts.ClassDeclaration) {
for (const member of node.members) {
if (
!ts.isMethodDeclaration(member) ||
!ts.isIdentifier(member.name) ||
!HOOKS_TO_INTERFACES.hasOwnProperty(member.name.text)
) {
continue;
}
const requiredInterface = HOOKS_TO_INTERFACES[member.name.text];
const hasRequiredInterface = node.heritageClauses?.some(
clause =>
clause.token === ts.SyntaxKind.ImplementsKeyword &&
clause.types.some(
type =>
ts.isExpressionWithTypeArguments(type) &&
ts.isIdentifier(type.expression) &&
type.expression.text === requiredInterface,
),
);
if (!hasRequiredInterface) {
this.addFailureAtNode(
node.name || node,
`Class must implement interface ${requiredInterface}, because it uses Angular lifecycle hook ${member.name.text}`,
);
}
}
return super.visitClassDeclaration(node);
}
}