Real World Example

Real World: Typed API data in a job portal

In company projects the API response is described with types, so a typo like job.salry is caught by the editor before the app runs.

type Job = { id: number; title: string; company: string; salary?: number; remote: boolean };

type RequestState<T> =
  | { status: 'loading' }
  | { status: 'error'; message: string }
  | { status: 'success'; data: T };

function JobList({ state }: { state: RequestState<Job[]> }) {
  if (state.status === 'loading') return <p>Loading...</p>;
  if (state.status === 'error') return <p>{state.message}</p>;
  return <ul>{state.data.map((job) => <li key={job.id}>{job.title} at {job.company}</li>)}</ul>;
}