@@ -38,7 +38,7 @@ export class InitializerApiUsageRule implements SourceFileValidatorRule {
3838 } ) ;
3939 }
4040
41- checkNode ( node : ts . Node ) : ts . Diagnostic [ ] | null {
41+ checkNode ( node : ts . Node ) : ts . Diagnostic | null {
4242 // We only care about call expressions.
4343 if ( ! ts . isCallExpression ( node ) ) {
4444 return null ;
@@ -50,9 +50,7 @@ export class InitializerApiUsageRule implements SourceFileValidatorRule {
5050 node = node . parent ;
5151 }
5252
53- // Initializer functions are allowed to be used in the initializer.
54- if ( ! node . parent || ! ts . isCallExpression ( node ) ||
55- ( ts . isPropertyDeclaration ( node . parent ) && node . parent . initializer === node ) ) {
53+ if ( ! node . parent || ! ts . isCallExpression ( node ) ) {
5654 return null ;
5755 }
5856
@@ -62,13 +60,36 @@ export class InitializerApiUsageRule implements SourceFileValidatorRule {
6260 return null ;
6361 }
6462
65- return [
66- makeDiagnostic (
67- ErrorCode . UNSUPPORTED_INITIALIZER_API_USAGE , node ,
68- `Unsupported call to the ${ identifiedInitializer . api . functionName } ${
69- identifiedInitializer . isRequired ?
70- '.required' :
71- '' } function. This function can only be called in the initializer of a class member.`)
72- ] ;
63+ const functionName = identifiedInitializer . api . functionName +
64+ ( identifiedInitializer . isRequired ? '.required' : '' ) ;
65+
66+ if ( ts . isPropertyDeclaration ( node . parent ) && node . parent . initializer === node ) {
67+ let closestClass : ts . Node = node . parent ;
68+
69+ while ( closestClass && ! ts . isClassDeclaration ( closestClass ) ) {
70+ closestClass = closestClass . parent ;
71+ }
72+
73+ if ( closestClass && ts . isClassDeclaration ( closestClass ) ) {
74+ const decorators = this . reflector . getDecoratorsOfDeclaration ( closestClass ) ;
75+ const isComponentOrDirective = decorators !== null && decorators . some ( decorator => {
76+ return decorator . import ?. from === '@angular/core' &&
77+ ( decorator . name === 'Component' || decorator . name === 'Directive' ) ;
78+ } ) ;
79+
80+ return isComponentOrDirective ?
81+ null :
82+ makeDiagnostic (
83+ ErrorCode . UNSUPPORTED_INITIALIZER_API_USAGE , node ,
84+ `Unsupported call to the ${
85+ functionName } function. This function can only be used as the initializer ` +
86+ `of a property on a @Component or @Directive class.` ) ;
87+ }
88+ }
89+
90+ return makeDiagnostic (
91+ ErrorCode . UNSUPPORTED_INITIALIZER_API_USAGE , node ,
92+ `Unsupported call to the ${
93+ functionName } function. This function can only be called in the initializer of a class member.`) ;
7394 }
7495}
0 commit comments