TypeScript
Back to journalTypeScript

TypeScript discriminated unions: the pattern I reach for daily

Jan 09, 20256 min readHSHarshal Singh

How a small modeling discipline turns runtime branches into compile-time guarantees — and makes refactors fearless.

Most TypeScript bugs I see in code review boil down to the same thing: a state was modeled as a bag of optional fields when it should have been a discriminated union.

The shape

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

Now you can't accidentally read .data while loading. The compiler stops you. That's the whole game.

Tagged

#TypeScript#Patterns
HS

Harshal Singh

Software Engineer · Mumbai, India

Get in touch

Keep reading

All posts →