Back to Articles
2024-01-1010 min read

Advanced TypeScript Design Patterns

TypeScriptDesign PatternsAdvanced

Explore advanced TypeScript patterns and techniques to write more robust and type-safe applications.

Advanced TypeScript Design Patterns

TypeScript provides powerful features for implementing design patterns. Let's explore advanced techniques.

Builder Pattern

The Builder pattern creates complex objects step by step:

class QueryBuilder {
  private query: string = '';

  select(fields: string[]): this {
    this.query += `SELECT ${fields.join(', ')} `;
    return this;
  }

  from(table: string): this {
    this.query += `FROM ${table} `;
    return this;
  }

  where(condition: string): this {
    this.query += `WHERE ${condition}`;
    return this;
  }

  build(): string {
    return this.query;
  }
}

// Usage
const query = new QueryBuilder()
  .select(['name', 'email'])
  .from('users')
  .where('active = true')
  .build();

Generic Repository Pattern

Create type-safe data access:

interface Repository<T> {
  findById(id: string): Promise<T | null>;
  findAll(): Promise<T[]>;
  save(entity: T): Promise<T>;
  delete(id: string): Promise<void>;
}

class UserRepository implements Repository<User> {
  // Implementation
}

Discriminated Unions

Type-safe state handling:

type Result<T> =
  | { status: 'success'; data: T }
  | { status: 'error'; error: Error };

function handleResult<T>(result: Result<T>) {
  if (result.status === 'success') {
    console.log(result.data);
  } else {
    console.error(result.error);
  }
}

Conclusion

These patterns leverage TypeScript's type system for safer, more maintainable code.