Unions, Literals and Narrowing
Values that can be one of several types, exact-value types, and how TypeScript follows your if-statements to know which one you hold. Tagged unions, exhaustive checks and custom guards.
Real programs are full of values that can be one of several things: an id that is a number or a text, a request that is loading, done or failed, a shape that is a circle or a square. This phase teaches the tool for that: the union type, written A | B.
A union is only useful if you can find out which one you are holding. TypeScript does this by reading your if statements, switch statements and checks like typeof and instanceof, and narrowing the type inside each branch. You will learn every kind of narrowing, then the most useful pattern in all of TypeScript: the discriminated union, a union with a shared tag, which the compiler can check for completeness.
Every example is checked by the real TypeScript compiler. Predict the type before you look at the Types panel, then change the code and see how narrowing follows you.
Practise this phase
Hands-on exercises: write the code, see your page live, and press Check to have it tested automatically.