Lesson 4 of 7
Builder Pattern in TypeScript
The Builder pattern constructs complex objects step by step. TypeScript's type system can enforce that a builder's `build()` method is only callable after all required fields have been set - using conditional return types and phantom types to track builder state at the type level.
Builder Pattern - Fluent Interface & Type-Safe Construction
// ── Basic fluent builder ─────────────────────────────────────
class TaskBuilder {
private task: Partial<Task> = {};
withTitle(title: string): this {
this.task.title = title;
return this;
}
withPriority(priority: Priority): this {
this.task.priority = priority;
return this;
}
withStatus(status: TaskStatus): this {
this.task.status = status;
return this;
}
withDueDate(dueDate: Date): this {
this.task.dueDate = dueDate;
return this;
}
withTags(...tags: string[]): this {
this.task.tags = tags;
return this;
}
build(): Task {
if (!this.task.title) throw new Error("Task requires a title");
return {
id: Date.now(),
title: this.task.title,
description: this.task.description ?? null,
status: this.task.status ?? "todo",
priority: this.task.priority ?? "medium",
assignee: null,
dueDate: this.task.dueDate ?? null,
tags: this.task.tags ?? [],
createdAt: new Date(),
updatedAt: new Date(),
} as Task;
}
}
// Usage:
const task = new TaskBuilder()
.withTitle("Design API")
.withPriority("high")
.withDueDate(new Date("2026-05-01"))
.withTags("backend", "api")
.build(); // ✅ Task
// ── Type-safe query builder ────────────────────────────────────
class TaskQueryBuilder {
private filters: Partial<{ status: TaskStatus; priority: Priority; assigneeId: number }> = {};
private paginationOptions = { page: 1, perPage: 20 };
private sortOptions: { field: keyof Task; direction: "asc" | "desc" } | null = null;
whereStatus(status: TaskStatus): this {
this.filters.status = status;
return this;
}
wherePriority(priority: Priority): this {
this.filters.priority = priority;
return this;
}
paginate(page: number, perPage = 20): this {
this.paginationOptions = { page, perPage };
return this;
}
sortBy(field: keyof Task, direction: "asc" | "desc" = "asc"): this {
this.sortOptions = { field, direction };
return this;
}
async execute(repo: ITaskRepository): Promise<{ items: Task[]; total: number }> {
return repo.findPaginated({
...this.filters,
...this.paginationOptions,
sort: this.sortOptions ?? undefined,
});
}
}
// Usage:
const urgentTasks = await new TaskQueryBuilder()
.whereStatus("in-progress")
.wherePriority("critical")
.sortBy("dueDate", "asc")
.paginate(1, 10)
.execute(taskRepo);Common Mistakes
- Returning `this` type but not the concrete class - if a subclass extends the builder, `return this` must be typed as `this` (not the parent class) for method chaining to return the subclass.
- Not validating in `build()` - the builder accumulates partial state. Always validate all required fields in `build()` and throw a clear, specific error for any missing required field.
- Using a builder when a simple object literal works - builders shine for complex objects with many optional fields and validation. For simple objects, a typed factory function is cleaner.
Tip
Tip
Practice Builder Pattern in TypeScript in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Builder Pattern in TypeScript
Practice Task
Note
Practice Task - (1) Write a working example of Builder Pattern in TypeScript from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Builder Pattern in TypeScript is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- The Builder pattern constructs complex objects step by step.
- Returning `this` type but not the concrete class - if a subclass extends the builder, `return this` must be typed as `this` (not the parent class) for method chaining to return the subclass.
- Not validating in `build()` - the builder accumulates partial state. Always validate all required fields in `build()` and throw a clear, specific error for any missing required field.
- Using a builder when a simple object literal works - builders shine for complex objects with many optional fields and validation. For simple objects, a typed factory function is cleaner.
Finished this lesson?