Builder
A builder is an object that collects configuration through fluent methods and then produces a value. In TypeScript the type of the builder can grow as you set fields, so a missing required field is a compile error on build().
Detailed Explanation
The JavaScript builder is a class with setters that return this and a build() that returns the product. TypeScript types that in two ways.
The simple way: a class with this return types and a build(): Product. Required fields are either constructor arguments or checks inside build() that throw. The type of build() is always Product, even when you forgot url(). You have a fluent API and a runtime check.
The typed way: the builder is generic over the fields that have been set. Each setter returns a new type that intersects a flag. build() is only present (or only returns Product rather than never) when the flags include the required keys.
type With<K extends string> = { [P in K]: true };
class Req<S extends Record<string, true> = {}> {
url(u: string): Req<S & With<"url">> { return this as Req<S & With<"url">>; }
build(this: Req<With<"url">>): Request { ... }
}
new Req().build() is an error. new Req().url("/x").build() is a Request. This is a phantom-state builder. It is popular for query builders and SDK clients. It costs generic noise and as inside the setters (the runtime object is still this).
A third way is a single object accumulated with spreads, typed as Partial<Product> until a type guard or satisfies at the end. That is a builder without a class.
Use a builder when construction has many optional pieces and a few required ones, and when a telescoping constructor would be worse. Use this types so subclasses keep fluency. Do not use a builder for a two-field object; write a function.
The pattern does not allocate extra for the types. The class instance is the runtime cost. If every setter returns a new immutable copy, that is a real cost you chose.
Code Examples
1. Fluent builder with this.
// 1. Fluent builder with this.
type Request = { url: string; method: string };
class RequestBuilder {
private href = "";
private method = "GET";
url(value: string): this {
this.href = value;
return this;
}
post(): this {
this.method = "POST";
return this;
}
build(): Request {
if (this.href === "") throw new Error("url required");
return { url: this.href, method: this.method };
}
}
const req = new RequestBuilder().url("/pay").post().build();2. Phantom required-field: build only after url().
// 2. Phantom required-field: build only after url().
type HasUrl = { url: true };
class TypedBuilder<S extends object = {}> {
private href = "";
url(value: string): TypedBuilder<S & HasUrl> {
this.href = value;
return this as TypedBuilder<S & HasUrl>;
}
build(this: TypedBuilder<HasUrl>): { url: string } {
return { url: this.href };
}
}
const built = new TypedBuilder().url("/pay").build();3. Object-spread builder for small products.
// 3. Object-spread builder for small products.
function request(partial: Partial<Request> & Pick<Request, "url">): Request {
return { method: "GET", ...partial };
}
const r = request({ url: "/pay", method: "POST" });Common Gotchas
Phantom builders use `as` internally
the safety is on `build()`'s `this` type, not on the field assignments.
Returning the class name instead of `this` loses subclass methods
see this-types.
A throw in `build()` is still needed if the builder is used from JS
types are erased.
Immutable setters that copy the builder are `O(fields)` per call
measure if the chain is long.