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 };
}
}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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.