Docs
/
TypeScript
Chapter 9
09 — Type Assertions & Narrowing
Core Concepts
askeyword — tells TS to treat a value as a specific type- Non-null assertion (
!) — tells TS a value is not null/undefined - typeof guards —
typeof x === "string"narrows primitives - instanceof guards —
x instanceof Classnarrows to class instances inoperator —"key" in objnarrows to types that have that property- Custom type guards —
function isX(val): val is Xuser-defined narrowing - Assertion functions —
asserts val is Xthrows if not true, narrows after - Discriminated unions — shared literal field for switch narrowing
- Control flow analysis — TS tracks type through if/else/return/throw
Type Safety Hierarchy
| Method | Safety Level | Use When |
|---|---|---|
| typeof / instanceof | Safest | Primitive or class checks |
| Custom type guards | Safe | Complex object checks |
| Discriminated unions | Safe | Tagged unions with switch |
as assertion | Risky | You know more than TS |
as unknown as T | Dangerous | Forcing incompatible types |
! non-null | Risky | You're sure it's not null |