Type-Safe Builder Pattern
A builder that accumulates required fields in its type, refusing to compile a build call until every mandatory value has been supplied.
Code
export class RequestBuilder<HasUrl extends boolean, HasMethod extends boolean> {
private url = "";
private method = "GET";
private headers: Record<string, string> = {};
static create(): RequestBuilder<false, false> {
return new RequestBuilder<false, false>();
}
withUrl(this: RequestBuilder<false, HasMethod>, url: string): RequestBuilder<true, HasMethod> {
this.url = url;
return this as unknown as RequestBuilder<true, HasMethod>;
}
withMethod(this: RequestBuilder<HasUrl, false>, method: string): RequestBuilder<HasUrl, true> {
this.method = method;
return this as unknown as RequestBuilder<HasUrl, true>;
}
withHeader(key: string, value: string): this {
this.headers[key] = value;
return this;
}
build(this: RequestBuilder<true, true>): { url: string; method: string } {
return { url: this.url, method: this.method };
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.