AceDevHub
Functions & ModelingFree

Type Narrowing and Type Guards

Use typeof, in, instanceof, and custom type predicates so TypeScript understands which union member you handle in each branch.

IntermediateFreeNarrowing

Union types describe what a value might be; narrowing proves what it is in a branch. TypeScript performs control-flow analysis across if statements, early returns, and switch cases. Without narrowing, you cannot call string methods on string | number or access variant-specific fields safely.

Mastering guards is what makes unions practical. Built-in checks cover primitives and class instances; custom type predicates encapsulate validation logic reusable across modules — with the caveat that dishonest predicates break type safety silently.

typeof and truthiness

typeof handles string, number, boolean, bigint, symbol, undefined, and function. Remember typeof null is "object" — use explicit null checks. Truthiness removes null and undefined but also filters "", 0, and false — know what you intend to exclude.

typeof-narrow.ts
Loading editor…

in and instanceof

in checks property existence on object unions — pairs well with discriminant fields. instanceof narrows class instances — common for custom Error subclasses in service layers.

in-instanceof.ts
Loading editor…

Custom type predicates

Return type value is Type tells the compiler a true result means narrowed type. Use for unknown JSON and array filters that remove null — but implement predicates correctly or runtime lies to the type checker.

type-predicate.ts
Loading editor…
Outputconsole
admin@example.com
GuardBest for
typeofPrimitives
inObject unions
instanceofClasses
value is TCustom validation

Assignment and control-flow narrowing

TypeScript also narrows on assignment to const, discriminant equality, and array.includes checks on literal unions when configured. Each refinement persists until the variable is mutated or the scope ends.

  • typeof for primitives
  • in / discriminant for objects
  • instanceof for classes
  • Custom predicates for unknown input
  1. 1Narrow before member-specific access
  2. 2Truthiness removes null/undefined
  3. 3Predicates encode reusable checks
  4. 4Next: discriminated unions