Validating Object Shape with Type Predicates
What you'll learn: How to build a type predicate function that verifies an unknown object has all the required properties with the correct types before you use it.
Why This Matters
When working with unknown data (like API responses), you need to check not just that something is an object, but that it has the exact shape you expect. A comprehensive type predicate validates each property's existence and type, giving you type safety for the entire object.
The Core Idea
Think of this like a security checkpoint with multiple stations. Each property needs to pass its own inspection before the entire object gets approved. Your type predicate function becomes a gatekeeper that says "yes, this unknown blob is actually a valid User object."
Here's a complete validation pattern:
interface User {
id: number;
name: string;
email: string;
isActive: boolean;
}
function isUser(value: unknown): value is User {
// First: is it even an object?
if (typeof value !== 'object' || value === null) {
return false;
}
// Now we know it's a non-null object
const obj = value as Record<string, unknown>;
// Check each required property exists and has the right type
return (
typeof obj.id === 'number' &&
typeof obj.name === 'string' &&
typeof obj.email === 'string' &&
typeof obj.isActive === 'boolean'
);
}
// Usage with unknown data
const apiData: unknown = JSON.parse('{"id":1,"name":"Alice","email":"alice@example.com","isActive":true}');
if (isUser(apiData)) {
// TypeScript now knows apiData is User
console.log(apiData.name.toUpperCase()); // Safe!
console.log(apiData.id + 100); // Safe!
}
Building Multi-Property Validators
The pattern scales to complex objects:
interface Product {
sku: string;
price: number;
inStock: boolean;
}
function isProduct(value: unknown): value is Product {
if (typeof value !== 'object' || value === null) {
return false;
}
const obj = value as Record<string, unknown>;
return (
typeof obj.sku === 'string' &&
typeof obj.price === 'number' &&
typeof obj.inStock === 'boolean'
);
}
Each property check acts as a requirement. All must pass for the type predicate to return true.
The Key Pattern
- Check it's an object (not null, not primitive)
- Assert to Record<string, unknown> so you can access properties
- Validate each property with typeof or other guards
- Return the combined result with
&&
This creates a type-safe gateway from unknown to your specific type.
Key Takeaway: A well-built type predicate validates every required property's existence and type, transforming unsafe unknown data into a fully typed object you can confidently use.