Type a state machine with discriminated states
Model each state of a machine as a union member with its own fields, so impossible combinations cannot be written. Works in TypeScript 5.
A request with loading, data and error booleans can be loaded and failed at once. A union with one member per state cannot.
type Job =
| { status: 'idle' }
| { status: 'loading'; startedAt: number }
| { status: 'success'; data: string[] }
| { status: 'error'; message: string };
function describe(request: Job): string {
switch (request.status) {
case 'idle':
return 'waiting';
case 'loading':
return `loading since ${request.startedAt}`;
case 'success':
return `${request.data.length} items`;
case 'error':
return `failed: ${request.message}`;
}
}
console.log(describe({ status: 'success', data: ['a', 'b'] }));
console.log(describe({ status: 'error', message: 'timeout' }));2 items
failed: timeoutdata exists only on the success state, so reading request.data anywhere else is a compile error, and an error object cannot carry a data array by accident. The pattern is discriminated unions with status as the tag.
Transitions are not checked by this type: nothing stops code from going from idle straight to success. If the order matters, write a transition(from, event) function with its own union of events, or use a state machine library.