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.

TypescriptConfig Management

Code

typescriptsnippet
28 lines
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 };
  }
}

How the snippet works

The working surface is the class RequestBuilder — everything else is wiring.

The result comes back as an object carrying url.

Applying it

RequestBuilder is what another module would consume; nothing else here is load-bearing for callers.

The call returns url.

Statements that matter

return this as unknown as RequestBuilder<true, HasMethod>;
return this as unknown as RequestBuilder<HasUrl, true>;
return { url: this.url, method: this.method };

Interactive Tools for This Topic

FAQ

Does `RequestBuilder` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Is there an install step between copy and run?
No. Between copying and running there is nothing left to do.