TS UNIONSChapter 2 · TS Unions & Enums
Type Guards
TypeScript narrows a union whenever you check it: typeof x === "string", "swim" in pet, or value instanceof Date. When the check is too involved for that, write a type guard: a function whose return type is pet is Fish. Wherever it returns true, TypeScript treats the value as a Fish.
Worked example
How it reads
pet is Fishtells TypeScript what a true result means- In the true branch,
pet.swim()is allowed; in the false branch, only Bird is left "swim" in petchecks for the property at run time

Cloud tip: A type guard is only as honest as its body. If the check is wrong, TypeScript will trust it anyway.


