unknown in Type-Safe Validators
What you'll learn: How to build validator functions that accept unknown input and return narrowed, type-safe output—creating a protective boundary around untrusted data.
The Core Idea
A type-safe validator is a function that takes unknown input (representing data you don't trust yet—like JSON from an API or user input) and either:
- Returns a value with a narrowed type (like
Userornumber[]) if validation succeeds - Throws an error if validation fails
This pattern creates a clear "gate" in your code: everything before the validator deals with unknown, and everything after gets fully typed data you can trust.
The Pattern
function parseUser(data: unknown): User {
// Guard against non-objects
if (typeof data !== 'object' || data === null) {
throw new Error('User must be an object');
}
// Guard against missing properties
if (!('name' in data) || !('age' in data)) {
throw new Error('User must have name and age');
}
// Narrow and validate types
const { name, age } = data;
if (typeof name !== 'string') {
throw new Error('name must be a string');
}
if (typeof age !== 'number') {
throw new Error('age must be a number');
}
// Now safe to return as User
return { name, age };
}
// Usage - unknown in, User out
const apiData: unknown = JSON.parse('{"name":"Alice","age":30}');
const user = parseUser(apiData); // user is User
console.log(user.name); // ✓ Safe!
Why This Works
The validator acts like a security checkpoint. You're essentially telling TypeScript: "I'll do the runtime checks myself, and if this function returns without throwing, you can trust that the data matches this type."
Think of it like airport security—everything entering is "unknown passenger," but after screening, they're "verified traveler."
Key Takeaway: Validator functions transform unknown into specific types by performing runtime checks and throwing on failure, creating type-safe boundaries at your application's edges where external data enters.