简体   繁体   中英

TypeScript create object from generic type

I'm looking to create an object based on a generic type, but can't figure out the syntax. What I'm wanting is something like this contrived example:

myfunc<T>() : T[] {
    let obj = new T();
    let obj2 = new T();

    return [obj, obj2];
}

The new T() of course doesn't compile. In C# I'd add a where T : new constraint to make that work. What's the equivalent in TypeScript?

You have to remember that TypeScript types (including generics) only exist at compile time. Also, in JavaScript the constructor function is of a different type that the object it constructs.

You probably are looking for something like this (assuming your constructor takes zero parameters):

function foo<T>(C: { new(): T }): T[] {
    return [new C(), new C()];
}

class SomeClass {}

// here you need to pass the constructor function
const array = foo(SomeClass);

There, C is the constructor function you will use at runtime and T is a type that will be inferred as the resulting of the construction.

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