control flow analysis
The compiler following every branch, return and throw in your code to work out the narrowest type a variable can have at each line.
In more detail
After if (!param) return, the compiler knows param is truthy for the rest of the function. Early returns, throws, typeof checks and equality comparisons all feed into it. It is what makes narrowing automatic.
Related terms
- type narrowing — The compiler refining a broad type to a more specific one inside a block, after a check proves which case applies.
- type guard — A run time check, such as typeof x === "string" or a custom function, that the compiler uses to narrow a type.
- truthy — A value that counts as true in a condition such as if (value), which is every value except the falsy ones.
Taught in
- Tuples: Fixed Length, Labeled Elements And Variadic Tuples — Production TypeScript
- Typeof Guards, Truthiness And Equality Narrowing — Production TypeScript
- Assertion Signatures: asserts condition And Invariants — Production TypeScript
- Exhaustive Narrowing With never In Production Handlers — Production TypeScript
- The Spine Artifact: Generating Typed Models From OpenAPI — Production TypeScript