Docs
/
TypeScript
Chapter 9

09 — Type Assertions & Narrowing

Core Concepts

  • as keyword — tells TS to treat a value as a specific type
  • Non-null assertion (!) — tells TS a value is not null/undefined
  • typeof guardstypeof x === "string" narrows primitives
  • instanceof guardsx instanceof Class narrows to class instances
  • in operator"key" in obj narrows to types that have that property
  • Custom type guardsfunction isX(val): val is X user-defined narrowing
  • Assertion functionsasserts val is X throws 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

MethodSafety LevelUse When
typeof / instanceofSafestPrimitive or class checks
Custom type guardsSafeComplex object checks
Discriminated unionsSafeTagged unions with switch
as assertionRiskyYou know more than TS
as unknown as TDangerousForcing incompatible types
! non-nullRiskyYou're sure it's not null