File tree Expand file tree Collapse file tree
ng-generate/inject-migration Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -533,7 +533,7 @@ function migrateInjectDecorator(
533533
534534 // `inject` no longer officially supports string injection so we need
535535 // to cast to any. We maintain the type by passing it as a generic.
536- if ( ts . isStringLiteralLike ( firstArg ) ) {
536+ if ( ts . isStringLiteralLike ( firstArg ) || isStringType ( firstArg , localTypeChecker ) ) {
537537 typeArguments = [ type || ts . factory . createKeywordTypeNode ( ts . SyntaxKind . AnyKeyword ) ] ;
538538 injectedType += ' as any' ;
539539 } else if (
@@ -885,3 +885,10 @@ function replaceParameterReferencesInInitializer(
885885
886886 return result . join ( 'this.' ) ;
887887}
888+
889+ function isStringType ( node : ts . Expression , checker : ts . TypeChecker ) : boolean {
890+ const type = checker . getTypeAtLocation ( node ) ;
891+
892+ // stringLiteral here is to cover const strings inferred as literal type.
893+ return ! ! ( type . flags & ts . TypeFlags . String || type . flags & ts . TypeFlags . StringLiteral ) ;
894+ }
Original file line number Diff line number Diff line change @@ -120,7 +120,7 @@ describe('inject migration', () => {
120120 ] ) ;
121121 } ) ;
122122
123- it ( 'should account for string tokens in @Inject()' , async ( ) => {
123+ it ( 'should account for string literal tokens in @Inject()' , async ( ) => {
124124 writeFile (
125125 '/dir.ts' ,
126126 [
@@ -145,6 +145,35 @@ describe('inject migration', () => {
145145 ] ) ;
146146 } ) ;
147147
148+ it ( 'should account for string tokens in @Inject()' , async ( ) => {
149+ writeFile (
150+ '/dir.ts' ,
151+ [
152+ `import { Directive, Inject } from '@angular/core';` ,
153+ `` ,
154+ `const token = 'not-officially-supported'` ,
155+ `` ,
156+ `@Directive()` ,
157+ `class MyDir {` ,
158+ ` constructor(@Inject(token) private foo: number) {}` ,
159+ `}` ,
160+ ] . join ( '\n' ) ,
161+ ) ;
162+
163+ await runMigration ( ) ;
164+
165+ expect ( tree . readContent ( '/dir.ts' ) . split ( '\n' ) ) . toEqual ( [
166+ `import { Directive, inject } from '@angular/core';` ,
167+ `` ,
168+ `const token = 'not-officially-supported'` ,
169+ `` ,
170+ `@Directive()` ,
171+ `class MyDir {` ,
172+ ` private foo = inject<number>(token as any);` ,
173+ `}` ,
174+ ] ) ;
175+ } ) ;
176+
148177 it ( 'should account for injected generic parameters' , async ( ) => {
149178 writeFile (
150179 '/dir.ts' ,
You can’t perform that action at this time.
0 commit comments