As you write TypeScript, the compiler will intelligently look at the flow of your logic and how it branches out and, if possible, will attempt to narrow down the type of different variables. It starts by inspecting the widest type a variable can have, and then depending on how it is used with JavaScript keywords such as instanceof / typeof / if / else / return / switch
it narrows down to a more specific type.