Unions and Literal Types
A union means the value can be type A or type B.
Like a box that can hold either an apple or an orange.
Literal types go further.
The value must be one of a fixed set of exact words or numbers.
Union types
Write A | B.
The bar means OR.
Before you treat the value as one branch, narrow it.
Narrow means look closer until you know which one it is.
String and number literals
A literal type is one exact value.
Instead of any string, allow only the words you really use.
Typos become compile errors instead of quiet bugs.
Combining with object shapes
Unions of objects let a value be one of several shapes.
Give them a shared tag field so narrowing is easy.
A tag is a label that says which shape you have.
We go deeper in Discriminated Unions.
Literal widening
Widen means the exact word becomes a wider string type.
const often keeps the exact literal type.
let may widen a string literal to string.
Write a type when you need the narrow set of options to stick.
Why unions help
Unions put real choices into the type system.
Invalid options never compile.
That keeps your mental map small and honest.
Unions and literals put choices into the type system. Invalid options never compile.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.