Advertisement
Intermediate TypeScript, Discriminated Unions & Exhaustiveness Checking

How would you model API response states (loading, success, error) as a discriminated union?

Short answer

Define a union where each state variant has the same discriminant key (e.g. 'status') with a different literal value, plus only the data relevant to that specific state — this prevents accessing 'data' before checking status is 'success', or 'error' before checking status is…

Save TypeScript mock interview
Advertisement
AModel answer
Define a union where each state variant has the same discriminant key (e.g. 'status') with a different literal value, plus only the data relevant to that specific state — this prevents accessing 'data' before checking status is 'success', or 'error' before checking status is 'error'.
type RequestState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; error: string };

function render(state: RequestState<User>) {
  if (state.status === 'success') console.log(state.data); // safe access
}
Real-world example
Modeling a data-fetching hook's state so consuming components can't accidentally access 'data' while still loading.
Likely follow-ups
  • How does this compare to representing the same state with several separate optional boolean flags?
Related topics