Type guards narrow types at runtime. Here's how to use them effectively.
typeof Guard#
instanceof Guard#
in Operator#
Discriminated Unions#
Custom Type Guards#
Assertion Functions#
Generic Type Guards#
Narrowing with Control Flow#
Zod Runtime Validation#
Best Practices#
Guards:
✓ Use discriminated unions when possible
✓ Keep type guards focused
✓ Use assertion functions for validation
✓ Combine with Zod for runtime safety
Patterns:
✓ Prefer 'in' over type assertion
✓ Use exhaustiveness checking
✓ Create reusable type guards
✓ Document complex guards
Avoid:
✗ Type assertions without validation
✗ Overly complex type predicates
✗ Ignoring null/undefined
✗ Trusting external data
Conclusion#
Type guards enable safe type narrowing at runtime. Use typeof for primitives, instanceof for classes, and discriminated unions for complex types. Custom type guards with type predicates provide flexibility, while assertion functions enforce invariants. Combine with Zod for robust runtime validation.