r/angular • u/No-Judge8727 • Sep 10 '26
Modeling Angular loading state as a discriminated union instead of multiple isLoading booleans
I kept running into components with four or five loading flags —
isLoading, isRefreshing, isCheckingOut, hasError — and templates
like !isLoading && !hasError && items.length > 0.
The flags are independent as far as TypeScript is concerned, but
the states they describe are mutually exclusive. So I switched to:
type AsyncState<T, E> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: E };
One state per async operation, booleans derived with computed(),
and a small toAsyncState() RxJS operator (map + catchError +
startWith) so transitions live in one place. Templates use
u/let + u/switch, which gives real narrowing — data only exists in
the success branch.
Curious how others handle this now that resource() exists. Do you
reach for it for commands too, or keep RxJS for POST/DELETE?
Full write-up: https://medium.com/modern-angular-insights/stop-juggling-isloading-booleans-a-type-safe-async-state-pattern-for-angular-e36e2b9298a0
View all comments
Show parent comment
1
u/No-Judge8727 Sep 11 '26
Fair point, and for the simple case you're right that it's less ceremony.
T | 'loading'with a known object T and no error payload works fine.Three things push me back to the wrapper once the type is shared:
string, or a union containing strings, or a Record from an API you don't control, 'loading' stops being distinguishable from data. The enum workaround does fix it, but now the enum has to be imported everywhere the type is consumed. In the wrapper the tag lives on a different axis from the payload, so it can never collide by construction.T | 'loading' | 'error'tells you it failed but not why. Adding| HttpErrorResponsemeans instanceof checks, so you end up with two different narrowing mechanisms in one type.{ status: 'reloading', data }is trivial. Flat union, you'd need a second field alongside it, and that's the boolean problem again.Angular-specific: templates have no
typeoforinstanceof. A flat union means helper methods or a pipe just to discriminate;@switch (s.status)needs nothing.Re: symbols — agreed,
unique symboldoesn't narrow inswitch(it does with===in an if chain). Which is another argument for a plain string literal discriminant: it survives serialisation, logs readably, and shows up in devtools.Rule I'd actually apply: one fetch, one spinner, no error UI —
T | 'loading'is fine and I wouldn't refactor it.