·13 min
Advanced TypeScript Patterns for React Applications
TypeScript patterns that catch bugs at compile time and improve developer experience in React applications.
Discriminated Unions
type FormState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: FormData }
| { status: 'error'; error: string }
function FormStatus({ state }: { state: FormState }) {
switch (state.status) {
case 'idle': return <Form />
case 'loading': return <Spinner />
case 'success': return <Success data={state.data} /> // data is typed
case 'error': return <Error message={state.error} /> // error is typed
}
}Zod for Runtime Validation
import { z } from 'zod'
const UserSchema = z.object({
name: z.string().min(2),
email: z.string().email(),
age: z.number().int().positive(),
role: z.enum(['admin', 'member', 'viewer']),
})
type User = z.infer<typeof UserSchema>
function validateUser(input: unknown): User {
return UserSchema.parse(input) // throws if invalid
}Template Literal Types
type EventName = `on${Capitalize<string>}`
type CSSProperty = `${'margin' | 'padding'}-${'top' | 'bottom' | 'left' | 'right'}`Type-Safe API Patterns
type ApiResponse<T> = { success: true; data: T } | { success: false; error: string }
async function fetchApi<T>(url: string): Promise<ApiResponse<T>> {
const res = await fetch(url)
return res.json()
}
const result = await fetchApi<User[]>('/api/users')
if (result.success) {
result.data.forEach(u => console.log(u.name)) // fully typed
}The Bottom Line
The Frontend Platform Kit from BreafIO provides type-safe patterns. The SaaS Starter Kit uses Zod for validation. The Admin Dashboard Pro demonstrates discriminated unions. The API Boilerplate provides type-safe API routes, and the Component Library Starter uses advanced TypeScript for component props.
Ready to Build?
Get started with our production-ready starter kits and ship your project faster.
Browse Starter Kits