What are type guards in TypeScript

· Category: TypeScript

Short answer

Type guards are expressions that narrow the type of a variable within a conditional block, allowing safe access to type-specific members.

Steps

  1. Use typeof for primitives: if (typeof value === 'string') { ... }
  2. Use instanceof for classes: if (error instanceof HttpError) { ... }
  3. Use in for object properties: if ('id' in obj) { ... }
  4. Write custom type predicate functions: function isString(x: unknown): x is string { ... }
  5. Use discriminated unions with a shared literal property for exhaustive checks.

Tips

  • Custom type predicates are powerful for API response validation and domain modeling.
  • Combine type guards with early returns to flatten nested conditionals.

Common issues

  • instanceof checks fail across realms like iframes or VM contexts.
  • Type guards only narrow within the scope where the condition is true; reassignment can invalidate the narrowed type.