How can I get around using multiple constructors within a component? Currently I am getting the error:
'Multiple constructor implementations are not allowed'.
questions: any[];
constructor( service: QuestionSignupStepOneService ) {
this.questions = service.getQuestions();
}
constructor( service: QuestionSignupStepOneAService ) {
this.questions = service.getQuestions();
}
Is there anyway to simplify what I am trying to do? The code compiles properly but will only run through the first service, ignoring the second.
Edit in 2021: I realized long ago that this was a silly question, but I'm leaving this up because if I did not understand constructors enough so to ask the question then other might find themselves here as well
error TS2392: Multiple constructor implementations are not allowed.
In TypeScript, we cannot define multiple constructors like other programming languages because it does not support multiple constructors.
Making multiple constructors with the same parameters doesn't make sense unless they have different types, in Typescript you can do the following:
class Foo {
questions: any[];
constructor(service: QuestionSignupStepOneService, param2?: Param2Type) {
this.questions = service.getQuestions();
if(param2){
console.log(param2);
}
}
}
This is equal to two constructors, the first one is new Foo(service)
and the second one is new Foo(service, param2)
.
Use ?
to state that the parameter is optional.
If you want two constructors with the same parameter but for different types you can use this:
class Foo {
questions: any[];
constructor(service: QuestionSignupStepOneService | QuestionSignupStepOneAService) {
if(service instanceof QuestionSignupStepOneService){
this.questions = service.getQuestions();
}
else {
this.questions = service.getDifferentQuestions();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With