TypeScript Patterns Every Backend Dev Should Know

Alex Chen
•
March 30, 2026
•
12 min read
•
114 views

TypeScript Patterns Every Backend Dev Should Know

TypeScript's type system is far more powerful than most developers realize. Here are patterns that will make your backend code safer and more expressive.

1. Discriminated Unions for API Responses

type ApiResponse<T> =
  | { success: true; data: T }
  | { success: false; error: string; code: number }

function handleResponse<T>(response: ApiResponse<T>) {
  if (response.success) {
    // TypeScript knows response.data exists here
    return response.data
  }
  // TypeScript knows response.error exists here
  throw new Error(response.error)
}

2. Branded Types for Domain Safety

type UserId = string & { readonly __brand: 'UserId' }
type OrderId = string & { readonly __brand: 'OrderId' }

function createUserId(id: string): UserId {
  return id as UserId
}

// This prevents accidentally passing an OrderId where a UserId is expected
function getUser(id: UserId) { /* ... */ }

3. Builder Pattern with Method Chaining

class QueryBuilder<T> {
  private filters: Record<string, unknown> = {}
  private sortField?: string
  private limitCount?: number

  where(field: keyof T, value: unknown): this {
    this.filters[field as string] = value
    return this
  }

  orderBy(field: keyof T): this {
    this.sortField = field as string
    return this
  }

  limit(count: number): this {
    this.limitCount = count
    return this
  }
}

Key Takeaways

  • Use the type system as documentation
  • Prefer compile-time errors over runtime errors
  • Types should make invalid states unrepresentable
Alex Chen

Alex Chen

Senior software engineer passionate about clean code and refactoring legacy systems. 10+ years of experience turning spaghetti into maintainable architectures.