When to Use Assertion Functions
You'll learn: When assertion functions are the right choice for enforcing conditions that should never fail during execution.
The Right Tool for Critical Guarantees
Assertion functions are like security checkpoints at an airport — they're not for everyday validation where you expect some passengers to be turned away. They're for catching situations that indicate something has gone fundamentally wrong with your program's logic.
Think of them as "this should be impossible unless there's a bug" checks.
Use Assertion Functions For:
Invariants
Conditions that must always be true at certain points in your code:
function assertPositive(value: number): asserts value is number {
if (value <= 0) {
throw new Error(`Expected positive number, got ${value}`);
}
}
function calculateDiscount(price: number) {
assertPositive(price); // Prices should NEVER be non-positive here
// If we reach this line, price is guaranteed positive
return price * 0.1;
}
Preconditions
Requirements that must hold before a function can safely execute:
function assertConfigured(config: unknown): asserts config is { apiKey: string } {
if (!config || typeof config !== 'object' || !('apiKey' in config)) {
throw new Error('Application not properly configured');
}
}
function makeApiCall(config: unknown) {
assertConfigured(config); // MUST have valid config or halt immediately
// Now we can safely use config.apiKey
return fetch('/api', { headers: { key: config.apiKey } });
}
When NOT to Use Them
Don't use assertion functions for expected validation scenarios like user input or external data — those should return errors or use type guards instead.
Key Takeaway: Use assertion functions for invariants and preconditions that represent programmer errors or corrupted state — situations where halting execution immediately is the safest response.