Type-safe builder pattern in Typescript - Time & Space Complexity
We want to understand how the time it takes to build an object grows as we add more steps in a type-safe builder pattern.
How does the number of builder method calls affect the total work done?
Analyze the time complexity of the following TypeScript builder pattern code.
class Builder {
private parts: string[] = [];
addPart(part: string): this {
this.parts.push(part);
return this;
}
build(): string {
return this.parts.join(", ");
}
}
This code builds a string by adding parts one by one, then joining them all at the end.
Look for loops or repeated work in the builder.
- Primary operation: Adding parts to an array and joining them.
- How many times: Each addPart call adds one element; build joins all parts once.
As you add more parts, the work to join them grows with the number of parts.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Adding 10 parts + joining 10 parts |
| 100 | Adding 100 parts + joining 100 parts |
| 1000 | Adding 1000 parts + joining 1000 parts |
Pattern observation: The joining step grows linearly with the number of parts added.
Time Complexity: O(n)
This means the total work grows in a straight line as you add more parts to the builder.
[X] Wrong: "Each addPart call does a lot of work, so the builder is slow."
[OK] Correct: Each addPart just adds one item quickly; the main work happens once when build() joins all parts.
Understanding how builder patterns scale helps you design clean and efficient code, a skill valued in many coding challenges.
"What if the build() method joined parts multiple times during building? How would that affect time complexity?"
Practice
What is the main benefit of using a type-safe builder pattern in TypeScript?
Solution
Step 1: Understand the purpose of type-safe builder pattern
The pattern helps build objects step-by-step while ensuring correctness.Step 2: Identify the key benefit
It uses TypeScript's type system to check that all required properties are set before final object creation.Final Answer:
It ensures all required properties are set before creating the object. -> Option AQuick Check:
Type safety = required properties checked [OK]
- Thinking it improves runtime speed
- Confusing it with UI generation
- Assuming it removes interfaces
Which of the following is the correct way to declare a generic builder class in TypeScript?
class Builder<T> {
private data: T;
constructor() {
this.data = {} as T;
}
build(): T {
return this.data;
}
}Solution
Step 1: Check generic class declaration
class Builder<T> { private data: T; constructor() { this.data = {} as T; } build(): T { return this.data; } } correctly declares a generic class with<T>and initializesdataas{} as T.Step 2: Verify build method return type
Thebuild()method returnsdatatyped asT, matching the generic type.Final Answer:
class Builder<T> { private data: T; constructor() { this.data = {} as T; } build(): T { return this.data; } } -> Option CQuick Check:
Generic class with typed data = class Builder<T> { private data: T; constructor() { this.data = {} as T; } build(): T { return this.data; } } [OK]
<T> and proper initialization [OK]- Using any instead of generic type
- Initializing data with null or undefined
- Missing generic parameter in class
Consider this TypeScript code using a type-safe builder pattern:
interface User {
name: string;
age: number;
}
class UserBuilder {
private user = {} as Partial<User>;
setName(name: string) { this.user.name = name; return this; }
setAge(age: number) { this.user.age = age; return this; }
build(): User {
if (!this.user.name || !this.user.age) throw new Error('Missing fields');
return this.user as User;
}
}
const user = new UserBuilder().setName('Alice').setAge(30).build();
console.log(user);What will be the output?
Solution
Step 1: Trace method calls on UserBuilder
The builder setsnameto 'Alice' andageto 30, so both required fields are set.Step 2: Check build method behavior
Since both fields exist, no error is thrown, and the object is returned asUser.Final Answer:
{ name: 'Alice', age: 30 } -> Option AQuick Check:
All fields set = object returned [OK]
- Assuming error thrown even when fields set
- Expecting undefined output
- Missing age property in output
Identify the error in this type-safe builder pattern code and select the fix:
interface Car {
make: string;
year: number;
}
class CarBuilder {
private car = {} as Partial<Car>;
setMake(make: string) { this.car.make = make; return this; }
setYear(year: number) { this.car.year = year; return this; }
build(): Car {
if (!this.car.make || !this.car.year) throw new Error('Missing fields');
return this.car;
}
}Solution
Step 1: Identify the type mismatch in build()
The method returnsthis.carwhich is typed asPartial<Car>, but the return type isCar.Step 2: Fix by casting to Car
To satisfy the return type, castthis.carasCarafter checking required fields.Final Answer:
Cast return value as Car: return this.car as Car; -> Option DQuick Check:
Return type must match method signature [OK]
- Changing return type to Partial<Car>
- Removing validation checks
- Initializing with full Car without setting fields
You want to create a type-safe builder for a Product with required id and name, and optional description. Which approach best enforces setting required fields before build?
interface Product {
id: number;
name: string;
description?: string;
}
// Which builder pattern enforces required fields at compile time?Solution
Step 1: Understand compile-time enforcement
Only generics with flags and conditional types can enforce required fields before build at compile time.Step 2: Compare options
Use generics with flags tracking set fields and conditional types for build() uses TypeScript generics and conditional types to track which fields are set, preventing build() call until required fields are set.Final Answer:
Use generics with flags tracking set fields and conditional types for build() -> Option BQuick Check:
Compile-time safety = generics + conditional types [OK]
- Relying only on runtime checks
- Using inheritance without generics
- Returning partial objects without enforcement
Ready to prove it?
Pass the test and this pattern moves unknown
