Radu Catalin-Andrei’s Post

View profile for Radu Catalin-Andrei

🌍 Senior Full-Stack Engineer | B2B SaaS platforms with React, Next.js & Node.js | Headless CMS Integrations | Performance & Multi-Tenant Systems | Scalable Web Architectures | 7+ Years | B2B Contractor

Most TypeScript devs reach for "any" when types get complex. There's a cleaner fix: discriminated unions. Instead of a type with optional fields (data, error, loading) that might all be undefined at the same time, you model each state explicitly with a shared "status" field. Something like: - { status: 'loading' } - { status: 'error', error: string } - { status: 'success', data: User } Now TypeScript knows exactly what's available in each branch. No more optional chaining and null fallbacks everywhere. Your switch statements get exhaustiveness checking for free. This pattern shines in React. When your component renders based on fetch status, each arm of the union is a compiler-enforced contract. You cannot accidentally access data while in an error state. I use this constantly in B2B SaaS apps where complex async flows are the norm. It cuts runtime surprises significantly. Bonus tip: add a never exhaustiveness check in your switch default and you'll catch missing cases at compile time, not in production. What is your go-to TypeScript pattern for managing complex async state? #TypeScript #React #WebDevelopment

To view or add a comment, sign in

Explore content categories