Assertion functions narrow types by throwing on invalid conditions. Here's how to use them.
Basic Assertion Functions
Common Assertion Functions
Interface Assertions
Discriminated Union Assertions
Conditional Assertions
Error Classes
Runtime Invariants
Combining with Type Guards
API Response Validation
Best Practices
Design:
✓ Clear error messages
✓ Use custom error classes
✓ Preserve stack traces
✓ Document assertion behavior
Usage:
✓ Validate at boundaries
✓ Assert invariants
✓ Use for required values
✓ Combine with type guards
Performance:
✓ Assertions can be stripped in production
✓ Keep validation logic simple
✓ Avoid expensive checks in hot paths
✓ Consider lazy validation
Avoid:
✗ Silent failures
✗ Overly complex assertions
✗ Assertions for flow control
✗ Ignoring assertion errors
Conclusion
Assertion functions provide runtime type checking with TypeScript type narrowing. Use them for validating external data, enforcing invariants, and ensuring type safety at runtime. Combine with custom error classes and clear messages for better debugging.