Gre*_*man 1 javascript constructor class function typescript
I want to be able to instantiate objects in javascript (typescript) from a reference to the class. For instance, I want to be able to use some kind of factory function like so, but I don't know how to achieve this result.
class A {
constructor() { this.b = 'somevalue'; }
}
const factory = (klass: Function) => {
return new klass();
}
const instanceOfA = factory(A);
Run Code Online (Sandbox Code Playgroud)
This example is rather contrived, but is there a way of doing this? The current error says klass is not a constructor. Alternatively if there's a more idiomatic way of instantiating things from a class reference, I'd love to hear it. Thanks!
Function is just the wrong type, use a constructor type (which also helps infering the correct return type):
function factory<T>(klass: { new(): T }): T {
return new klass();
}
Run Code Online (Sandbox Code Playgroud)
Or as a const you assign to:
const factory = <T>(klass: { new(): T }) => {
return new klass();
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |