Course contentsShow
← TypeScript
Lesson 1432 of 1,79632. Advanced PatternsFree lesson

The build() Method and Final Type Inference

Implement type-safe build() methods that return precise types based on all accumulated builder state.

The build() Method and Final Type Inference

What you'll learn: How to implement a build() method that returns precisely the right type based on everything accumulated in your builder chain.

The Final Puzzle Piece

You've been constructing a sophisticated builder pattern, chaining methods that progressively accumulate state. But here's the critical moment: when you call build(), TypeScript needs to look at everything you've done and return exactly the right type—not a vague approximation, not a union of possibilities, but the precise shape that reflects your builder's current configuration.

Why build() Type Inference Matters

Without careful design, your build() method might return a generic type that doesn't reflect which methods you called:

// Bad: loses precision
const config = builder
  .setName("app")
  .setPort(3000)
  .build(); // Returns some generic Config type

With proper final type inference, TypeScript remembers what you built:

// Good: precise type inference
const config = builder
  .setName("app")
  .setPort(3000)
  .build(); // Returns { name: string; port: number } exactly

Implementing Type-Safe build()

The build() method typically uses the accumulated type state (often tracked through a generic parameter) to determine its return type:

type Builder<T extends Record<string, unknown>> = {
  withName<N extends string>(name: N): Builder<T & { name: N }>;
  withPort<P extends number>(port: P): Builder<T & { port: P }>;
  build(): T;
};

The return type T reflects all the properties accumulated through the chain. When you call build(), TypeScript infers exactly what T is at that moment.

The Pattern in Action

type BuilderState<T extends Record<string, unknown>> = {
  with<K extends string, V>(key: K, value: V): BuilderState<T & Record<K, V>>;
  build(): T;
};

declare function createBuilder<T extends Record<string, unknown>>(): BuilderState<T>;

const result = createBuilder()
  .with("enabled", true)
  .with("timeout", 5000)
  .build();

// result type: { enabled: boolean; timeout: number }

Notice how the final type of result precisely captures both properties and their literal types.

Key Takeaway: The build() method's return type should reference the builder's accumulated generic state parameter, ensuring TypeScript infers the exact final shape based on the complete method chain, not a generic approximation.