Back to Blog
TypeScriptTypesAssertionsValidation

TypeScript Assertion Functions

Master TypeScript assertion functions. From type narrowing to runtime checks to invariants.

B
Bootspring Team
Engineering
May 29, 2020
7 min read

Assertion functions narrow types by throwing on invalid conditions. Here's how to use them.

Basic Assertion Functions

Loading code block...

Common Assertion Functions

Loading code block...

Interface Assertions

Loading code block...

Discriminated Union Assertions

Loading code block...

Conditional Assertions

Loading code block...

Error Classes

Loading code block...

Runtime Invariants

Loading code block...

Combining with Type Guards

Loading code block...

API Response Validation

Loading code block...

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.

Share this article

Help spread the word about Bootspring

Related articles