Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 multiple constructor implementations are not allowed TS2392

Tags:

angular

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

like image 328
eric-blue Avatar asked Dec 07 '16 22:12

eric-blue


People also ask

Can we have multiple constructors in angular?

error TS2392: Multiple constructor implementations are not allowed.

Can we have multiple constructors in TypeScript?

In TypeScript, we cannot define multiple constructors like other programming languages because it does not support multiple constructors.


1 Answers

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(); 
    }
  }
}
like image 130
Murhaf Sousli Avatar answered Nov 15 '22 20:11

Murhaf Sousli