Runtime Validation
Problem
Data from external sources like APIs, user input, or local storage is assumed to match expected types without verification. Invalid data crashes the application when accessed, causes silent bugs when used in calculations, or corrupts state when stored. TypeScript types provide no protection at runtime, allowing malformed data to flow through the system unchecked.
Solution
Validate data at runtime rather than relying solely on types, catching issues with external data. This protects against malformed API responses and user input that bypasses compile-time checks.
Example
This example demonstrates runtime validation that verifies user data matches expected formats, catching invalid data from APIs or user input before it corrupts the application.
function validateUser(data) {
// Verify age is a valid positive number
if (typeof data.age !== 'number' || data.age < 0) {
throw new Error('Invalid age');
}
// Basic email format validation
if (!data.email.includes('@')) {
throw new Error('Invalid email');
}
// Return validated data
return data;
}
Benefits
- Catches invalid data from APIs, users, or storage at runtime.
- Provides protection that TypeScript types cannot offer for external data.
- Prevents corrupt data from flowing through the application.
- Enables graceful error handling when data doesn’t match expectations.
Tradeoffs
- Adds runtime overhead to validate data on every use.
- Can be verbose with manual validation code for complex objects.
- Requires maintaining validation logic separately from types.
- May duplicate validation between client and server.