0
0
Typescriptprogramming~7 mins

Builder pattern with generics in Typescript

Choose your learning style9 modes available
Introduction

The builder pattern helps you create complex objects step-by-step. Using generics makes it flexible for different types.

When you want to create objects with many optional parts.
When you want to reuse the building steps for different object types.
When you want to avoid long constructor parameter lists.
When you want clear and readable code for object creation.
When you want to enforce type safety while building objects.
Syntax
Typescript
class Builder<T> {
  private object: Partial<T> = {};

  set<K extends keyof T>(key: K, value: T[K]): this {
    this.object[key] = value;
    return this;
  }

  build(): T {
    return this.object as T;
  }
}

Partial<T> means the object can have some or all properties of T.

The set method uses generics to ensure the key and value match the object type.

Examples
Builds a Person object by setting name and age.
Typescript
interface Person {
  name: string;
  age: number;
}

const personBuilder = new Builder<Person>();
personBuilder.set('name', 'Alice').set('age', 30);
const person = personBuilder.build();
Builds a Car object with required properties. Optional properties can be skipped.
Typescript
interface Car {
  brand: string;
  year: number;
  color?: string;
}

const carBuilder = new Builder<Car>();
carBuilder.set('brand', 'Toyota').set('year', 2022);
const car = carBuilder.build();
Sample Program

This program builds a House object step-by-step using the builder pattern with generics. It sets windows, doors, and garage presence, then prints the final object.

Typescript
interface House {
  windows: number;
  doors: number;
  hasGarage: boolean;
}

class Builder<T> {
  private object: Partial<T> = {};

  set<K extends keyof T>(key: K, value: T[K]): this {
    this.object[key] = value;
    return this;
  }

  build(): T {
    return this.object as T;
  }
}

const houseBuilder = new Builder<House>();
houseBuilder
  .set('windows', 4)
  .set('doors', 2)
  .set('hasGarage', true);

const house = houseBuilder.build();

console.log(house);
OutputSuccess
Important Notes

Using generics keeps the builder flexible and type-safe for any object shape.

The Partial<T> type allows building the object piece by piece.

Always call build() to get the final object.

Summary

The builder pattern helps create complex objects step-by-step.

Generics make the builder reusable for different object types.

TypeScript ensures keys and values match the object properties.