Make illegal states unrepresentable with types
Make illegal states unrepresentable with types in TypeScript: model each state with only the fields it can have. Node.js 24.
A request type with loading, data and error fields allows nonsense such as loading with an error. A union gives each state only its own fields.
type Request =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: string[] }
| { status: 'failure'; error: string };
function show(request: Request): string {
switch (request.status) {
case 'idle': return 'press the button';
case 'loading': return 'loading...';
case 'success': return `${request.data.length} results`;
case 'failure': return `failed: ${request.error}`;
}
}
console.log(show({ status: 'success', data: ['a', 'b'] }));
console.log(show({ status: 'failure', error: 'timeout' }));2 results
failed: timeoutdata exists only on success and error only on failure, so you cannot read data while loading, and you cannot build a value that has both. The switch covers every status, and adding a fifth status makes show fail to compile because the return type no longer holds.
Node.js 24 strips the types when it runs the file, so run tsc --noEmit to see these checks. Types are erased at run time, so data from outside still needs validation.