Teach TypeScript a reusable narrowing rule.
Section: Narrowing and Control Flow
Custom type guard with predicate
typescript
typescript
type User = { id: number; name: string };
const isUser = (value: unknown): value is User => {
return typeof value === "object" && value !== null && "id" in value && "name" in value;
};Explanation
Type predicates are useful for validation boundaries like JSON input or external APIs.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Narrowing and Control Flow
Narrow with `instanceof`
Refine class-based unions using constructor checks.
Narrow with the `in` operator
Refine unions by checking property existence.
Type an async function
Return a typed promise from an async function.