TSworkingts-evergreen
Type Narrowing
Trust the compiler.
TypeScript narrows union types based on the operations you use against them — typeof, instanceof, in, and custom type guards. Knowing the rules saves casts.
typeof and in
TSintro Press Run to execute
typeof a === 'string' peels the string off the parameter, then 'lives' in a and 'goodBoy' in a pick out the object variants by a property only they have — producing named Whiskers, cat with 9 lives, good dog, fish. Inside each branch a is narrowed enough that a.lives and a.goodBoy are accessible without a cast.