fix(ivy): handle overloaded constructors in ngtsc (#34590)
Currently ngtsc looks for the first `ConstructorDeclaration` when figuring out what the parameters are so that it can generate the DI instructions. The problem is that if a constructor has overloads, it'll have several `ConstructorDeclaration` members with a different number of parameters. These changes tweak the logic so it looks for the constructor implementation. PR Close #34590
This commit is contained in:
@ -35,8 +35,12 @@ export class TypeScriptReflectionHost implements ReflectionHost {
|
||||
getConstructorParameters(clazz: ClassDeclaration): CtorParameter[]|null {
|
||||
const tsClazz = castDeclarationToClassOrDie(clazz);
|
||||
|
||||
// First, find the constructor.
|
||||
const ctor = tsClazz.members.find(ts.isConstructorDeclaration);
|
||||
// First, find the constructor with a `body`. The constructors without a `body` are overloads
|
||||
// whereas we want the implementation since it's the one that'll be executed and which can
|
||||
// have decorators.
|
||||
const ctor = tsClazz.members.find(
|
||||
(member): member is ts.ConstructorDeclaration =>
|
||||
ts.isConstructorDeclaration(member) && member.body !== undefined);
|
||||
if (ctor === undefined) {
|
||||
return null;
|
||||
}
|
||||
@ -564,4 +568,4 @@ function getExportedName(decl: ts.Declaration, originalId: ts.Identifier): strin
|
||||
return ts.isImportSpecifier(decl) ?
|
||||
(decl.propertyName !== undefined ? decl.propertyName : decl.name).text :
|
||||
originalId.text;
|
||||
}
|
||||
}
|
||||
|
@ -211,6 +211,29 @@ runInEachFileSystem(() => {
|
||||
expect(args.length).toBe(1);
|
||||
expectParameter(args[0], 'bar', {moduleName: './bar', name: 'Bar'});
|
||||
});
|
||||
|
||||
it('should reflect the arguments from an overloaded constructor', () => {
|
||||
const {program} = makeProgram([{
|
||||
name: _('/entry.ts'),
|
||||
contents: `
|
||||
class Bar {}
|
||||
class Baz {}
|
||||
|
||||
class Foo {
|
||||
constructor(bar: Bar);
|
||||
constructor(bar: Bar, baz?: Baz) {}
|
||||
}
|
||||
`
|
||||
}]);
|
||||
const clazz = getDeclaration(program, _('/entry.ts'), 'Foo', isNamedClassDeclaration);
|
||||
const checker = program.getTypeChecker();
|
||||
const host = new TypeScriptReflectionHost(checker);
|
||||
const args = host.getConstructorParameters(clazz) !;
|
||||
expect(args.length).toBe(2);
|
||||
expectParameter(args[0], 'bar', 'Bar');
|
||||
expectParameter(args[1], 'baz', 'Baz');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user