1

In typescript I pass whole class as reference MyClass to a function. How to create new instance of that class in that function?

export class MyClass {
}

createClass(MyClass);

function createClass(classReference) {
   const classInstance = new classReference();//not working
}

I need it because in angular's ModuleWithProviders I cannot call new MyClass().

2 Answers 2

2

It should look like this:

function createClass<T>(classReference: { new (): T }): T {
   return new classReference();
}

let a = createClass(MyClass); // type of a is MyClass

(code in playground)

Sign up to request clarification or add additional context in comments.

Comments

0

In your ModuleWithProviders you could instead use:

{ provide: ProviderToReplace, useClass: MyClass }

See more here

2 Comments

Thanks for reply. I know that but that class is not a provider - it's array of classes with mostly data.
That makes sense, I'll leave this here in case it solves someone else's problem 😊

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.