I've been diving into the world of asynchronous constructors and have successfully implemented them in JavaScript.
However, I'm facing a challenge with TypeScript types. Here's how it should ideally work:
const a: AnyClass = await AnyClass.create();
While this setup works perfectly in JavaScript, the TypeScript types are currently missing.
Let's consider the example of a similar class named 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 foundation class is as follows:
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;
}
}
My question is, what type should be specified for the return value of the create
method?