Error Handling When Validation Fails
What you'll learn: How to safely respond when unknown data doesn't match the shape you expect, using either thrown errors or result types.
Why This Matters
When you validate unknown data from APIs or user input, validation can fail. You need a plan for what happens next. TypeScript can help you handle failures type-safely, ensuring callers know what to expect and how to handle problems.
Two Core Strategies
1. Throwing Descriptive Errors
The simplest approach: if validation fails, throw an error immediately. This works well when invalid data is truly exceptional.
function assertIsUser(value: unknown): asserts value is { name: string; age: number } {
if (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string" &&
"age" in value &&
typeof value.age === "number"
) {
return;
}
throw new Error("Invalid user data: expected { name: string, age: number }");
}
// Usage
function processApiResponse(data: unknown): void {
assertIsUser(data); // Throws if invalid
console.log(data.name); // Safe: data is now narrowed
}
The error message tells developers (and logs) exactly what went wrong.
2. Returning Result Types
For more controlled error handling, return an object that represents success or failure. This makes validation failures explicit in the type system.
type Success<T> = { success: true; data: T };
type Failure = { success: false; error: string };
type Result<T> = Success<T> | Failure;
function validateUser(value: unknown): Result<{ name: string; age: number }> {
if (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string" &&
"age" in value &&
typeof value.age === "number"
) {
return { success: true, data: value };
}
return { success: false, error: "Invalid user shape" };
}
// Usage
const result = validateUser(apiData);
if (result.success) {
console.log(result.data.name); // Type-safe access
} else {
console.error(result.error); // Handle failure gracefully
}
This pattern forces callers to handle both paths explicitly—no forgotten error handling.
Choosing Your Approach
- Throw errors when invalid data is a bug or truly unexpected
- Return result types when validation failure is a normal flow (bad user input, optional fields)
Key Takeaway: When unknown validation fails, either throw descriptive errors for exceptional cases or return discriminated union result types to make error handling explicit and type-safe.