Full Stack 28:302025-10-20
TypeScript Patterns Every React Developer Should Know
Stop fighting TypeScript. These patterns — discriminated unions, generics for components, proper event types — will make your code safer and your IDE smarter.
Watch on YouTube
Click to open in YouTube
Video Notes & Code
Key takeaways, code snippets, and resources from this video.
Discriminated Unions for State Machines
typescript
type AsyncState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: string }
// Now TypeScript narrows correctly
function render<T>(state: AsyncState<T>) {
if (state.status === 'success') {
return state.data // T — correctly typed
}
if (state.status === 'error') {
return state.error // string
}
}Generic Components
tsx
interface ListProps<T> {
items: T[]
renderItem: (item: T) => React.ReactNode
keyExtractor: (item: T) => string
}
function List<T>({ items, renderItem, keyExtractor }: ListProps<T>) {
return (
<ul>
{items.map(item => (
<li key={keyExtractor(item)}>{renderItem(item)}</li>
))}
</ul>
)
}
// Usage — fully type-safe
<List<User>
items={users}
keyExtractor={u => u.id}
renderItem={u => <span>{u.name}</span>}
/>Found this useful?
Subscribe for weekly content on AI engineering, SaaS building, and full stack development.