TypeScript Discriminated Union Builder
Define union variants visually. Get type-safe TypeScript with switch statements, type guards, and exhaustive checking.
Union Configuration
Variants
Frequently Asked Questions
What is a discriminated union in TypeScript?▼
A discriminated union (also called a tagged union or algebraic data type) is a union type where each member has a common literal property called the discriminant. TypeScript uses this discriminant field to narrow the type in switch/if statements, giving you exhaustive type checking. They model finite sets of states cleanly — like UI states (loading/success/error) or action types in reducers.
When should I use discriminated unions vs optional properties?▼
Use discriminated unions when your data has mutually exclusive states — never allow a combination that makes no sense in your domain. For example, don't use { data?: T, error?: Error, loading?: boolean } — use a union with discriminant 'status': 'loading' | 'success' | 'error'. This prevents impossible states at the type level and forces exhaustive handling.
What is exhaustive checking with never?▼
By adding a default case that assigns the discriminant to 'never', TypeScript will emit a compile error if you forget to handle a union member. Pattern: default: const _exhaustive: never = state; throw new Error('Unhandled state'). When you add a new state to the union, TypeScript will tell you exactly which switch statements need updating.
How do discriminated unions work with switch statements?▼
TypeScript narrows the type inside each case block based on the discriminant value. If the discriminant is 'status' and the case is 'success', TypeScript knows the full shape including success-only fields. This means you get autocomplete, null-checking, and type errors when accessing fields that don't exist in that state — without any runtime overhead.
What is the difference between discriminated unions and class inheritance?▼
Discriminated unions are pure data structures — plain objects with a type discriminant. They're serializable, immutable-friendly, and work great with JSON. Class inheritance requires instantiation and is harder to serialize. In functional TypeScript (Redux, Zustand, React reducers), discriminated unions are preferred. For OOP patterns with methods and polymorphism, classes are more appropriate.
Related Products
on GumroadDevPlaybook Interview Vault
210+ real technical interview questions with model answers, asked at Google, Meta, Amazon, Microsoft, Stripe, and Shopify. Covers Frontend (55), Backend (55), System Design (50), and DSA (50). Available in English and Traditional Chinese.
Buy on Gumroad →TypeScript Quick Reference Toolkit
5 practical reference files for TypeScript developers: cheatsheet, TS vs JS comparison, 20 utility types with real examples, tsconfig best practices template, and 15 common mistakes guide. Print it. Keep it on your desk.
Buy on Gumroad →Developer Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →You Might Also Need
TypeScript to JavaScript Converter
Strip TypeScript type annotations, interfaces, generics, enums, and decorators to convert TS to plain JavaScript. Client-side, no compilation needed, runs in your browser.
Open free tool →
SQL to TypeScript Types
Convert SQL CREATE TABLE statements to TypeScript interfaces and Zod schemas. Maps SQL column types to TypeScript with nullability.
Open free tool →
TanStack Query Config Builder
Configure TanStack Query (React Query v5) staleTime and gcTime visually. Generate QueryClient config and useQuery/useMutation TypeScript code with retry logic.
Open free tool →
More Free Tools
Related Articles
React Query + Zustand: The Server/Client State Separation Pattern in 2026
Stop fighting your state management. Learn how to correctly separate server state (React Query) from client state (Zustand) in React apps. Covers the mental model, integration patterns, optimistic updates, and architecture decisions for 2026.
SolidJS vs React 2026: Performance, DX, and When to Choose Each
Deep comparison of SolidJS and React in 2026: fine-grained reactivity vs virtual DOM, signals vs useState, performance benchmarks, SolidStart vs Next.js, and honest real-world tradeoffs.
Pinia vs Vuex vs Zustand: State Management in 2026
Comparing Pinia, Vuex, and Zustand for state management in 2026. Bundle size, TypeScript support, DevTools, and which to pick for your project.
Zod vs Yup vs Joi: The Definitive Validation Library Comparison (2026)
A comprehensive comparison of Zod, Yup, and Joi for TypeScript and JavaScript projects in 2026. Covers TypeScript inference, performance benchmarks, React Hook Form integration, tRPC, Fastify, and use-case recommendations.
Error Handling Patterns in JavaScript and TypeScript (2026 Guide)
Master error handling in JavaScript and TypeScript. Learn try/catch, Result/Either patterns, React error boundaries, custom error classes, async error handling, and the best error monitoring tools.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →