I have a base class that requires some parameters to be passed...
class BaseClass<ItemType> {
// Some irrelevant parameters omitted for simplicity...
constructor(__items: Iterable<ItemType>) {}
}
Now, I want to create a factory function that can return instances of this base class or its subclasses. The caller should also be able to specify which subclass they want instantiated with specific values provided for the omitted parameters. To achieve this, we declare an interface...
export interface GenericConstructorInterface<S, T extends BaseClass<S>> {
new(items: Iterable<S>): T;
}
With the interface in place, we can now define the factory function as follows...
// This implementation works fine...
export function factory<A, B extends BaseClass<A>>(__items: Iterable<A>, subclassConstructor: GenericConstructorInterface<A, B>): B {
return new subclassConstructor(__items);
}
However, if we wish to avoid requiring all callers to provide the constructor function, we might attempt...
// Attempting to use a default parameter leads to a type error:
// Type 'typeof BaseClass' is not assignable to type 'GenericConstructorInterface<A, B>'.
// Type 'BaseClass<A>' is not assignable to type 'B'.ts(2322)
export function factory<A, B extends BaseClass<A>>(__items: Iterable<A>, subclassConstructor: GenericConstructorInterface<A, B> = BaseClass): B {
return new subclassConstructor(__items);
}
The default parameter approach results in a type error. What am I missing here?