Unions & Narrowing
Model values that can be one of several shapes with union types, then narrow them with typeof and discriminated unions.
Step 1 of 7
When a value can be more than one thing
Some values genuinely have more than one type. An ID might be a string in one API and a number in another. A status field might be one of three exact strings. A function might return a result OR an error.
Union types model this with |: string | number, "loading" | "success" | "error", Result | ApiError.
Once you have a union, narrowing is how TypeScript lets you safely use it: by checking the type at runtime, the compiler knows which branch you’re in.
Learn more on MDN