Assertion Functions with unknown
You'll learn how to write assertion functions that validate unknown values and automatically narrow their types for the rest of the scope.
The Problem with unknown
You've seen how unknown forces you to check values before using them—but sometimes you want to throw an error if a value isn't what you expect, rather than handle both branches with type guards. That's where assertion functions shine with unknown inputs.
What Are Assertion Functions for unknown?
An assertion function with unknown input is a function that:
- Takes an
unknownvalue - Performs validation checks
- Throws an error if the validation fails
- Uses
assertssyntax to tell TypeScript "if this function returns, the value is safe"
After the assertion function returns normally, TypeScript automatically narrows the unknown type to whatever you asserted.
Basic Syntax
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== 'string') {
throw new Error('Value must be a string');
}
}
let data: unknown = getUserInput();
assertIsString(data);
// After this line, TypeScript knows data is string
console.log(data.toUpperCase()); // ✅ No error!
Real-World Pattern: JSON Validation
function assertIsUser(value: unknown): asserts value is { name: string; age: number } {
if (
typeof value !== 'object' ||
value === null ||
!('name' in value) ||
!('age' in value) ||
typeof value.name !== 'string' ||
typeof value.age !== 'number'
) {
throw new Error('Invalid user object');
}
}
const apiResponse: unknown = JSON.parse(someJson);
assertIsUser(apiResponse);
// apiResponse is now typed as { name: string; age: number }
console.log(apiResponse.name); // ✅ Safe
Why This Matters
Think of assertion functions as security checkpoints. When dealing with unknown data from external sources (APIs, user input, file parsing), you often want to say "this must be valid, or crash immediately." Assertion functions let you do this while teaching TypeScript what the value's type is after the check passes.
Key Takeaway: Assertion functions with unknown inputs validate data and throw on failure while simultaneously narrowing the type for all code that follows—providing both runtime safety and compile-time type information.