Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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?

like image 268
John Weisz Avatar asked Apr 08 '16 13:04

John Weisz


People also ask

Can a method return a class type java?

Every Method has a return type whether it is void, int, double, string or any other datatype. The getReturnType() method of Method class returns a Class object that represent the return type, declared in method at time of creating the method.

What is declare class in TypeScript?

declare class is for when you want to describe an existing class (usually a TypeScript class, but not always) that is going to be externally present (for example, you have two . ts files that compile to two . js files and both are included via script tags in a webpage).

How do you write a function inside a class in TypeScript?

Functions are general building blocks inside a class that hold some business logic. Creating a function in TypeScript is similar to the process in JavaScript: You use the function keyword. However, in TypeScript you also have the option to define the type of parameters and return type of the function.

What is Property in TypeScript?

Property in TypeScriptA property of a function type for each exported function declaration. A property of a constructor type for each exported class declaration. A property of an object type for each exported internal module declaration.


1 Answers

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'
like image 163
John Weisz Avatar answered Oct 13 '22 11:10

John Weisz