Built-in Assertion Patterns
What you'll learn: How to use common assertion function patterns that make your code safer and more readable.
The Common Patterns
Now that you understand how to write assertion functions, it's time to learn the patterns you'll see (and write) most often in TypeScript codebases. These reusable patterns handle the most frequent narrowing needs.
assertIsDefined
This pattern eliminates null and undefined:
function assertIsDefined<T>(value: T): asserts value is NonNullable<T> {
if (value === null || value === undefined) {
throw new Error('Value must be defined');
}
}
function processUser(user: string | undefined) {
assertIsDefined(user);
// TypeScript knows user is string here
console.log(user.toUpperCase());
}
assertIsString
This pattern narrows to a specific primitive:
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== 'string') {
throw new Error('Value must be a string');
}
}
function handleInput(input: unknown) {
assertIsString(input);
// TypeScript knows input is string
console.log(input.trim());
}
Generic assert Helper
A flexible pattern for any condition:
function assert(condition: unknown): asserts condition {
if (!condition) {
throw new Error('Assertion failed');
}
}
const data: string | null = getDataFromAPI();
assert(data !== null);
// TypeScript knows data is string here
console.log(data.length);
Why These Patterns Matter
Think of these as safety checkpoints in your code. Instead of scattering manual checks everywhere, these patterns give you reusable, type-safe validators that both runtime and TypeScript understand.
Key Takeaway: Common assertion patterns like assertIsDefined, assertIsString, and assert provide reusable building blocks for safe type narrowing throughout your codebase.