I'm trying to implement the Builder Patten similar to Java in TypeScript 4.6.2. From what I have read, this isn't the preferred way to do it, but I have some constrains regarding the module exports.
export class HttpRequest {
static Builder = class {
private body: string;
setBody(body: string): HttpRequest.Builder {
this.body = body;
return this;
}
build(): HttpRequest {
return new HttpRequest(this);
}
}
private readonly body: string;
constructor(builder: any) {
this.body = builder.body;
}
getBody(): string {
return this.body;
}
}
It seems that the setBody method can't return a HttpRequest.Builder type, with the following error:
TS2702: 'HttpRequest' only refers to a type, but is being used as a namespace here.
It seems to work fine if // @ts-ignore is present before the method declaration, or if the method signature is changed to setBody(body: string): any.
Is there any way to implement this with nested classes? I'm trying to avoid having two different classes, one for HttpRequest and one for Builder.