Generic Validation and Parsing
You'll learn how to build validators that don't just return true or false, but actually narrow types based on successful validation results.
The Core Idea
When you validate data (like user input or API responses), you usually want two things: to know if it's valid, and to use it safely with the correct type afterward. Generic validation combines type predicates with generics to transform unknown data into strongly-typed values in one step.
Instead of:
- Validate → get boolean
- Cast to type (unsafe!)
You get:
- Validate → get narrowed type or error
Building a Generic Validator
function validate<T>(
data: unknown,
check: (value: unknown) => value is T
): T {
if (check(data)) {
return data; // TypeScript knows data is T here
}
throw new Error("Validation failed");
}
// Type predicate helper
function isUser(value: unknown): value is { name: string; age: number } {
return (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string" &&
"age" in value &&
typeof value.age === "number"
);
}
const apiResponse: unknown = { name: "Alice", age: 30 };
const user = validate(apiResponse, isUser); // user: { name: string; age: number }
console.log(user.name.toUpperCase()); // Safe to use!
The generic <T> captures whatever type the predicate validates, and returns that exact type when successful.
Result-Based Parsing
type ParseResult<T> =
| { success: true; data: T }
| { success: false; error: string };
function parse<T>(
input: unknown,
validator: (v: unknown) => v is T
): ParseResult<T> {
if (validator(input)) {
return { success: true, data: input };
}
return { success: false, error: "Invalid format" };
}
Key Takeaway: Generic validators combine type predicates with generics to transform untyped data into safely-typed values, eliminating the need for unsafe type assertions after validation.