Skip to content

Commit cb442a0

Browse files
crisbetodylhunn
authored andcommitted
fix(migrations): account for parameters with union types (#57127)
This can up in Material where we had a `constructor(@optionA() foo: Foo | null)` which ended up producing incorrect code, because the union type was preserved. These changes resolve the issue by picking out the first non-literal type from the union for the `inject` call. PR Close #57127
1 parent 1cf616f commit cb442a0

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,8 @@ function createInjectReplacementCall(
319319
// they'll be specified as type arguments to `inject()`.
320320
if (ts.isTypeReferenceNode(type) && type.typeArguments && type.typeArguments.length > 0) {
321321
injectedType = type.typeName.getText();
322+
} else if (ts.isUnionTypeNode(type)) {
323+
injectedType = (type.types.find((t) => !ts.isLiteralTypeNode(t)) || type.types[0]).getText();
322324
} else {
323325
injectedType = type.getText();
324326
}

packages/core/schematics/test/inject_migration_spec.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1139,4 +1139,31 @@ describe('inject migration', () => {
11391139
`}`,
11401140
]);
11411141
});
1142+
1143+
it('should pick up the first non-literal type if a parameter has a union type', async () => {
1144+
writeFile(
1145+
'/dir.ts',
1146+
[
1147+
`import { Directive, Optional } from '@angular/core';`,
1148+
`import { Foo } from 'foo';`,
1149+
``,
1150+
`@Directive()`,
1151+
`class MyDir {`,
1152+
` constructor(@Optional() private foo: null | Foo) {}`,
1153+
`}`,
1154+
].join('\n'),
1155+
);
1156+
1157+
await runMigration();
1158+
1159+
expect(tree.readContent('/dir.ts').split('\n')).toEqual([
1160+
`import { Directive, Optional, inject } from '@angular/core';`,
1161+
`import { Foo } from 'foo';`,
1162+
``,
1163+
`@Directive()`,
1164+
`class MyDir {`,
1165+
` private foo = inject(Foo, { optional: true });`,
1166+
`}`,
1167+
]);
1168+
});
11421169
});

0 commit comments

Comments
 (0)