Skip to content

Commit de7aa60

Browse files
JeanMechepkozlowski-opensource
authored andcommitted
refactor(migrations): support local string tokens for inject migration (#62013)
The `localTypeChecker` allows us to at least support locally defined strings in addition to string literals. PR Close #62013
1 parent 4bba6d9 commit de7aa60

2 files changed

Lines changed: 38 additions & 2 deletions

File tree

‎packages/core/schematics/ng-generate/inject-migration/migration.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff 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+
}

‎packages/core/schematics/test/inject_migration_spec.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff 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',

0 commit comments

Comments
 (0)