How would you write a custom type guard that safely narrows an 'unknown' value into a specific, validated interface shape?
Short answer
Write a function with a `value is InterfaceName` return type predicate, performing thorough runtime checks (typeof, property existence, nested shape validation) against the unknown value — this bridges the gap between untyped external data and your application's actual typed…
Advertisement
AModel answer
Write a function with a `value is InterfaceName` return type predicate, performing thorough runtime checks (typeof, property existence, nested shape validation) against the unknown value — this bridges the gap between untyped external data and your application's actual typed domain models.
interface User { id: string; name: string; }
function isUser(value: unknown): value is User {
return (
typeof value === 'object' &&
value !== null &&
'id' in value && typeof (value as any).id === 'string' &&
'name' in value && typeof (value as any).name === 'string'
);
}
function handleResponse(data: unknown) {
if (isUser(data)) console.log(data.name); // safely narrowed to User
}Real-world example
Validating an untrusted API response's actual runtime shape before trusting it as a specific typed domain object.
Likely follow-ups
- How do runtime validation libraries like Zod or io-ts relate to this manual type-guard pattern, and what do they add?
Related topics