简体   繁体   中英

How do I instantiate a javascript object from class reference?

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);

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();
}

Or as a const you assign to:

const factory = <T>(klass: { new(): T }) => {
    return new klass();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM