I devised an abstract base class that facilitates asynchronous instantiation to load data before returning the instance. My goal is to prevent users from utilizing the constructor to avoid accessing an uninitialized instance, but I encountered the subsequent error when attempting to make the constructor protected:
The 'this' context of type 'typeof InheritedController' cannot be assigned to the method's 'this' type of 'Constructor'. It is not possible to assign a 'protected' constructor type to a 'public' constructor type.
This snippet showcases my code:
type Constructor<T> = new () => T;
export default abstract class BaseController {
static async create<T extends BaseController>(
this: Constructor<T>
): Promise<T> {
const controller = new this();
await controller.initialize();
return controller;
}
protected constructor() {}
protected async initialize() {
console.log('Initializing asynchronously...');
}
}
class InheritedController extends BaseController {
protected async initialize(): Promise<void> {
// Perform data loading process
}
}
const controller = await InheritedController.create()
I am puzzled by this error message and have yet to discover a viable solution.