Type for a function that takes a class as an argument and returns an instance of this class

I have an instant function that returns an instance of the provided class:

declare type ClassType = { new (): any }; // alias "ParameterlessConstructor" function getInstance(constructor: ClassType): any { return new constructor(); } 

How can I make a function return an constructor argument instance instead of any so that I can provide type safety for users of this function?

+2
source share
1 answer

Well, that was frivolous, I just had to get around the boundaries set by my own code.


The key indicates the constructor parameter as a new type that returns a generic type, which is the same generic type T returned by the getInstance function:

 function getInstance<T>(constructor: { new (): T }): T { return new constructor(); } 

This will give the correct results:

 class Foo { public fooProp: string; } class Bar { public barProp: string; } var foo: Foo = getInstance(Foo); // OK var bar: Foo = getInstance(Bar); // Error: Type 'Bar' is not assignable to type 'Foo' 
+2
source

Source: https://habr.com/ru/post/1242919/


All Articles