Discriminated Unions
A discriminated union is a union of object types with a shared tag.
A union means apple OR orange in one box.
The tag tells you which fruit is inside.
Switch or if on that tag. TypeScript then unlocks the right fields.
The tag pattern
Give every variant a field like kind or type.
A variant is one possible shape in the union.
Use a unique string literal for each one.
That single field drives narrowing.
Narrow means look closer until you know which one it is.
switch for clarity
switch on the discriminant scales well as you add variants.
A discriminant is the shared tag field.
Pair it with a never default to keep the union exhaustive.
Exhaustive means every option is handled.
Why not optional fields?
One object with many optional fields invites invalid mixes.
Success with an error message, and so on.
Discriminated unions make illegal states hard to write.
Illegal state means a mix that should never happen.
Building payloads
Network events, action objects, and UI state machines fit this pattern.
A payload is the data packet you send or store.
Name the tag the same way across the project.
Shared fields plus special fields
All variants can share some fields.
Each variant can also have its own special fields.
After you check the tag, those special fields unlock.
Tag every variant. Then let TypeScript prove you handled each case.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.