Skip to content
jshacks.dev
Patterns

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.

1 min read
Summarize in AI

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.

request.tsTypeScript
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' }));
Text
2 results
failed: timeout

data 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.

Taggednode 24
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.