Type guards narrow types at runtime, enabling TypeScript to understand what type a value is within a code block. Here's how to use them.
typeof Guards#
instanceof Guards#
in Operator Guards#
Custom Type Guards#
Array Type Guards#
Discriminated Unions#
Nullish Guards#
Assertion Functions#
Generic Type Guards#
API Response Guards#
Combining Guards#
Best Practices#
Built-in Guards:
✓ typeof for primitives
✓ instanceof for classes
✓ in for property checks
✓ Array.isArray for arrays
Custom Guards:
✓ Use type predicates (is)
✓ Validate thoroughly
✓ Handle edge cases
✓ Document expectations
Assertion Functions:
✓ Use for fail-fast validation
✓ Throw descriptive errors
✓ Use at boundaries
Avoid:
✗ Trusting external data
✗ Incomplete validation
✗ Overusing type assertions
✗ Ignoring null/undefined
Conclusion#
Type guards narrow types at runtime, enabling TypeScript to understand what type a value is within a code block. Use built-in guards (typeof, instanceof, in) for common cases, custom type predicates for complex types, and assertion functions for fail-fast validation. Discriminated unions with literal type discriminants provide exhaustive type checking. Always validate external data thoroughly and prefer type guards over type assertions for type safety.