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?
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.
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).
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With