Model UI states with discriminated unions
Represent only meaningful UI states
Several independent flags can allow contradictory states, such as loading and failed at the same time. A discriminated union groups each state with the data it actually needs. Every member has the same distinguishing field, here kind, with a different literal value. Checking that field narrows the possible shape. This is a type model, not an automatic state machine: transition rules still need code.
import React, {useState} from 'react';type Item={id:string;title:string};type Result={kind:'idle'}|{kind:'loading'}|{kind:'ready';items:Item[]}|{kind:'error';message:string};function ResultView({state}:{state:Result}){ switch(state.kind){ case 'idle':return <p>Choose a collection</p>; case 'loading':return <p role="status">Loading</p>; case 'ready':return state.items.length?<ul>{state.items.map(i=><li key={i.id}>{i.title}</li>)}</ul>:<p>No exhibits</p>; case 'error':return <p role="alert">{state.message}</p>; default:{const impossible:never=state;return impossible;} }}export default function App(){const [state,setState]=useState<Result>({kind:'idle'});return <section> <button onClick={()=>setState({kind:'loading'})}>Loading preview</button> <button onClick={()=>setState({kind:'ready',items:[{id:'a',title:'Ceramic bowl'}]})}>Result preview</button> <button onClick={()=>setState({kind:'ready',items:[]})}>Empty preview</button> <button onClick={()=>setState({kind:'error',message:'Collection unavailable'})}>Error preview</button><ResultView state={state}/></section>;}The buttons deliberately preview four outcomes without starting a network request. In ready, items is available and can be empty. In error, message is available. If a new variant is added, the never assignment catches an unhandled branch during semantic checking. This is not a guarantee of valid runtime objects or correct asynchronous transitions. Real requests also need cancellation and stale-response handling, covered earlier.
Validate outside data at the boundary
export type Exhibit = { id: string; title: string };export type ViewState = | { kind: 'idle' } | { kind: 'loading' } | { kind: 'ready'; items: Exhibit[] } | { kind: 'error'; message: string };export function parseExhibit(raw: unknown): Exhibit | null { if (typeof raw !== 'object' || raw === null) return null; if (!('id' in raw) || !('title' in raw)) return null; if (typeof raw.id !== 'string' || typeof raw.title !== 'string') return null; const id = raw.id.trim(), title = raw.title.trim(); return id && title ? { id, title } : null;}export function describe(state: ViewState): string { switch (state.kind) { case 'idle': return 'Choose a collection'; case 'loading': return 'Loading'; case 'ready': return state.items.length ? `${state.items.length} exhibits` : 'No exhibits'; case 'error': return state.message; default: { const impossible: never = state; return impossible; } }}This independent module does not import React. parseExhibit accepts unknown, rejects values without nonblank string fields, and returns a fresh object with trimmed fields. For example {id:" a ",title:" Lamp "} becomes {id:"a",title:"Lamp"}; null or a numeric id returns null. The parser assumes ordinary JSON-like objects, not arbitrary objects with throwing getters. describe handles each typed view state; the impossible branch is a compile-time exhaustiveness guard, not a runtime decoder. Test this module with strict TypeScript separately.
Turn an untrusted fixture into safe state
import React, {useState} from 'react';import {parseExhibit, describe} from './model';import type {ViewState} from './model';export default function App(){const [state,setState]=useState<ViewState>({kind:'idle'}); function load(raw:unknown){const item=parseExhibit(raw);setState(item?{kind:'ready',items:[item]}:{kind:'error',message:'Invalid exhibit'});} return <section><button onClick={()=>load({id:'a',title:'Lamp'})}>Load valid fixture</button> <button onClick={()=>load({id:9,title:'Lamp'})}>Load invalid fixture</button> <p role="status">{describe(state)}</p>{state.kind==='ready'&&<ul>{state.items.map(i=><li key={i.id}>{i.title}</li>)}</ul>}</section>;}This example requires the previous module saved as model.ts beside App.tsx. Load valid fixture shows 1 exhibits and Lamp; invalid fixture shows Invalid exhibit and removes the list. The count text is intentionally a simple fixed plural format. No external API is used. A type assertion on parsed JSON would merely tell the compiler to trust the value; it would not check the fields. A production validator may need stronger constraints, array bounds and a policy for unknown fields. Type checks do not replace runtime validation or authorization.
Practice
Add a cancelled variant and extend describe. Create a valid empty result and an invalid result missing items; explain which is rejected by the compiler. Test null, empty strings, numeric IDs and a valid trimmed exhibit using the parser.