John Weisz
John Weisz

Reputation: 31982

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

I have an instantiator 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 could I make it so that the function returns an instance of the constructor argument instead of any, so that I can achieve type safety for consumers of this function?

Upvotes: 5

Views: 791

Answers (1)

John Weisz
John Weisz

Reputation: 31982

Well, this was mortifyingly easy, I just had to bypass the boundaries set by my own code.


The key is specifying the constructor parameter to be a newable 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 yield 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'

Upvotes: 6

Related Questions