In TypeScript 4.6.2, I am working on incorporating the Builder Pattern similar to Java. While I have come across suggestions that this may not be the ideal approach, I have certain limitations when it comes to 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;
}
}
However, I have encountered an issue with the setBody
method not being able to return a HttpRequest.Builder
type, resulting in the error message:
TS2702: 'HttpRequest' only refers to a type, but is being used as a namespace here.
It appears that adding // @ts-ignore
before the method declaration or changing the method signature to setBody(body: string): any
resolves the issue.
My goal is to implement this using nested classes to avoid having separate classes for HttpRequest
and Builder
. Is there a way to achieve this?