I'm trying to create a class that takes multiple constructors like so:
class MyClass<T> {
constructor(ctors: (new (...args: any) => T)[]) {
}
}
This works, but when the class is instantiated I want its type to be a union of all provided constructors. So if I do
const x = new MyClass([Foo, Bar]);
I want x to be of type MyClass<Foo | Bar>. Right now the returned type is MyClass<Bar> for some reason. (playground)
How can I tell TypeScript that it should infer multiple types? I realise you can instantiate explicitly using new MyClass<Foo | Bar>([Foo, Bar]) but my actual use case is a lot more complex so I'd really wish for the type to be inferred implicitly.
I might be able to get away with the following:
class MyClass<T extends (new (...args: any) => any)[]> {
constructor(ctors: T) {
}
}
Which results in MyClass<(typeof Foo | typeof Bar)[]> (playground). But it's not pretty, so I'd prefer to get a type of MyClass<Foo | Bar> if possible.
MyClass<Foo>, notMyClass<Bar>.MyClass<Bar>.FooandBarbeing structurally equivalent so Typescript actually doesn't care which one is which. After I changed the field inBarfromxtoyso they are structurally distinct types, it gave meMyClass<Bar>instead.