I am working on the universal abstraction/base of the async constructor and it works fine with JavaScript.
But I'm stuck with correct TypeScript types, it should work like this:
const a: AnyClass = await AnyClass.create();
It works fine in JavaScript, but TypeScript types are wrong (missing at the moment).
Example of the similar class called DbConnection:
class DbConnection extends AsyncConstructor<[serverId: number, url: string]> {
#serverId: number;
#connection: Connection;
protected constructor(serverId: number, url: string) {
super(serverId, url);
this.#serverId = serverId;
}
protected override async constructorAsync(serverId: number, url: string): Promise<void> {
this.#connection = await DB.connect(url);
}
}
The base class is:
class AsyncConstructor<CtorParams extends any[]> {
protected constructor(...args: CtorParams) {}
protected async constructorAsync(...args: CtorParams): Promise<void> {
return Promise.resolve();
}
// =-->>> MISSING TYPES FOR THE NEXT METHOD: <<<--=
static async create(...args: CtorParams) {
const res = new this(...args);
await res.constructorAsync(...args);
return res;
}
}
What type to specify for the return of the create method?
implementsdeclaration, but it is possible to require them during thecreateinvocation. Have a look at stackoverflow.com/a/72771370/1048572 for example. Here, it could be something likeasync create<T>(this: { new(c: Connection): T; createConnection(): Promise<Connection> }): T { return new this(await this.createConnection()); }