All Challengesadvanced
TypeScript discriminated unions
Discriminated unions are how TypeScript models "one of several shapes". AI uses this for API responses and state machines.
typescriptdiscriminated unionstype narrowingswitch
typescript
type LoadingState = { status: 'loading' }
type SuccessState = { status: 'success'; data: string[] }
type ErrorState = { status: 'error'; message: string }
type State = LoadingState | SuccessState | ErrorState
function render(state: State): string {
switch (state.status) {
case 'loading':
return 'Loading...'
case 'success':
return state.data.join(', ')
case 'error':
return `Error: ${state.message}`
}
}Question
Why can you access state.data inside the "success" case but not outside the switch, and what happens if you forget a case?