After Exhaustive Runtime Validation
What you'll learn: How to safely assert types after runtime validation has confirmed data structure, creating a bridge between dynamic runtime checks and static compile-time guarantees.
When you validate data at runtime—whether through manual checks, validation libraries, or parsing functions—TypeScript doesn't automatically "know" that your data now matches a specific type. After exhaustive runtime validation, type assertions become a legitimate tool to inform the compiler about what your runtime logic has already proven.
The Pattern
The key insight: once you've thoroughly validated that unknown data matches your expected structure, you can assert the type without compromising safety:
function validateUser(data: unknown): data is { name: string; age: number } {
if (typeof data !== 'object' || data === null) return false;
if (typeof (data as any).name !== 'string') return false;
if (typeof (data as any).age !== 'number') return false;
return true;
}
function processApiData(rawData: unknown) {
if (!validateUser(rawData)) {
throw new Error('Invalid user data');
}
// After validation, assertion is safe
const user = rawData as { name: string; age: number };
console.log(user.name.toUpperCase());
}
This pattern bridges the gap between runtime safety (your validation logic) and compile-time safety (TypeScript's type system). The assertion isn't wishful thinking—it's documentation of what your validation already guaranteed.
When This Is Appropriate
- After comprehensive runtime type guards
- Following validation library checks
- When parsing external data with known structure
- After error-throwing validation functions
The validation does the real safety work; the assertion simply teaches TypeScript what you've already verified.
Key Takeaway: Type assertions after exhaustive runtime validation are legitimate because they document guarantees your code has already established—making runtime safety visible to the type system.