0

I am trying to create an instance of a class based on string input parameter.

for ex:

class Caller{
  constructor(private factory: IFactory){}
  
  getInstance(productType: string){
    var instance = factory.create(productType);
    console.log(instance);
  }
}



interface IService{}
class ServiceA implements IService{}
class ServiceB implements IService{}

class IFactory{
  create(productType: string): IService;
}

class Factory implements IFactory{
  create(productType: string): IService{
     // I want to return any child service class ServiceA/ServiceB instance here
     // I know I can do conditional instance creation by comparing input string to the type 
     // but don't want to do that
  }
}

I have seen and tried many other similar one's provided on SO, but nothing works for me like: Dynamically loading a typescript class (reflection for typescript)

OR

Creating Instance Of Class Based On ClassName : string

Thanks

5
  • "I have seen and tried many other similar one's provided on SO, but nothing works for me." This makes me suspect that if someone proposes a solution, you will be unhappy with it. Can you elaborate on exactly what doesn't work for you and why? Commented Jul 8, 2021 at 13:54
  • @jcalz have updated my question with couple of links Commented Jul 8, 2021 at 13:57
  • And why don't they work for you? Commented Jul 8, 2021 at 13:58
  • @jcalz giving errors in almost every case Commented Jul 8, 2021 at 14:02
  • That sounds like you couldn't figure out how to use the solutions, not that they are the wrong solutions for your problem. In that case, please edit the question to show your attempts and what errors you are getting. Commented Jul 8, 2021 at 14:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.