Advertisement
Advanced TypeScript, Mapped Types

How would you build a type-safe 'Builder' pattern using a mapped type that tracks which properties have already been set?

Short answer

Model the builder's state as a generic type parameter representing the set of already-set keys; each 'with' method returns a new builder type with that key added to the state (via a union or intersection update), and a 'build()' method is only made available (via a conditional…

Save TypeScript mock interview
Advertisement
AModel answer
Model the builder's state as a generic type parameter representing the set of already-set keys; each 'with' method returns a new builder type with that key added to the state (via a union or intersection update), and a 'build()' method is only made available (via a conditional type) once all required keys are present in the tracked state.
type Builder<T, Set extends keyof T = never> = {
  [K in keyof T]: (value: T[K]) => Builder<T, Set | K>
} & (Set extends keyof T ? { build(): T } : {});

// (Simplified illustration -- full implementation requires more advanced conditional plumbing)
Real-world example
Designing a fluent configuration builder API that only allows calling .build() once every required field has actually been set, enforced at compile time.
Likely follow-ups
  • Is this level of type-level state tracking common in real-world TypeScript codebases, or mostly a library-author technique?
Related topics