Model states with a discriminated union
Give each state its own object type with a literal status field, so success carries data and error carries a message and the compiler enforces it.
A request is idle, loading, done or failed, and only one of those has data. One interface with optional data and error lets impossible combinations exist. A union does not.
type FetchState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: string }
| { status: 'error'; message: string };
function render(state: FetchState): string {
switch (state.status) {
case 'idle':
return 'waiting';
case 'loading':
return 'loading...';
case 'success':
return state.data;
case 'error':
return `failed: ${state.message}`;
}
}
console.log(render({ status: 'success', data: 'hello' }));
console.log(render({ status: 'error', message: 'timeout' }));hello
failed: timeoutThe shared status field is the discriminant. Checking it in a switch narrows state to the one member with that literal, so state.data exists only in the success case. Writing { status: 'loading', data: 'x' } is an error, because that member has no data. See discriminated unions.
With strict on, the function needs no default: every case returns, so the compiler knows the end is unreachable. Add a member and render stops compiling until you handle it, which is the point of exhaustiveness checking.