Clean TypeScript code on a dark editor theme
Engineering Jul 15, 2024 6 min read

TypeScript Patterns I Use Every Day

Practical TypeScript patterns that have made my code more robust and my team more productive. No academic exercises—just battle-tested approaches.

Share:

TypeScript has transformed how I write JavaScript. But the real value isn't in the type system itself—it's in the patterns it enables. Here are the ones I reach for constantly.

Discriminated Unions for State

Instead of nullable fields and boolean flags, use discriminated unions. They make impossible states unrepresentable.

Instead of { data?: T; error?: Error; loading: boolean }, use { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: T } | { status: 'error'; error: Error }.

TypeScript code example
Discriminated unions make impossible states unrepresentable.

Branded Types for IDs

Prevent mixing up user IDs with post IDs by branding your types. It's a compile-time safeguard that costs nothing at runtime.

Const Assertions for Constants

Use as const to get literal types instead of widened types. Your constants become self-documenting and type-safe.

Utility Types I Use Constantly

  • Pick and Omit for reshaping types
  • Partial and Required for optional fields
  • Record for typed dictionaries
  • ReturnType for inferring function returns

"The best TypeScript code doesn't fight the type system—it leverages it."

The Meta-Lesson

Let the compiler catch bugs. Encode business rules in types. Make the pit of success as wide as possible.

Topics:

TypeScript programming patterns type safety JavaScript best practices

Author: Sahib Singh

Dubai-based Senior Software Engineer & Product Builder