API Response States
type ApiState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: string };
function handleState<T>(state: ApiState<T>) {
switch (state.status) {
case 'idle':
return 'Ready to fetch';
case 'loading':
return 'Loading...';
case 'success':
return state.data; // TypeScript knows data exists
case 'error':
return state.error; // TypeScript knows error exists
}
}Redux-style Actions
type Action = { type: 'INCREMENT' } | { type: 'DECREMENT' } | { type: 'SET'; payload: number };
function reducer(state: number, action: Action): number {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
case 'SET':
return action.payload; // payload is available
}
}Form Field Types
type FormField =
| { type: 'text'; value: string; maxLength?: number }
| { type: 'number'; value: number; min?: number; max?: number }
| { type: 'select'; value: string; options: string[] };
function renderField(field: FormField) {
if (field.type === 'select') {
return field.options.map((opt) => opt); // options available
}
}




