Generic Patterns in TypeScript
Generic Patterns in TypeScript
Section titled “Generic Patterns in TypeScript”Factory Pattern
Section titled “Factory Pattern”interface Factory<T> { create(): T;}
class UserFactory implements Factory<User> { create(): User { return { id: crypto.randomUUID(), name: "New User", email: "user@example.com", createdAt: new Date(), }; }}Builder Pattern
Section titled “Builder Pattern”class QueryBuilder<T> { private conditions: string[] = []; private limit?: number;
where(condition: string): this { this.conditions.push(condition); return this; }
take(n: number): this { this.limit = n; return this; }
async execute(): Promise<T[]> { const query = `SELECT * FROM ${this.table} WHERE ${this.conditions.join(" AND ")}`; return db.query(query); }}
const users = await new QueryBuilder<User>() .where("age > 18") .where("active = true") .take(10) .execute();Singleton + Registry Pattern
Section titled “Singleton + Registry Pattern”class ServiceRegistry { private static services = new Map<string, unknown>();
static register<T>(name: string, service: T): void { this.services.set(name, service); }
static get<T>(name: string): T { const service = this.services.get(name); if (!service) throw new Error(`Service ${name} not found`); return service as T; }}Interview Questions
Section titled “Interview Questions”Easy: What is the factory pattern with generics?
Medium: How does the builder pattern benefit from generics?
Hard: Design a type-safe service locator pattern with generics.