TypeScript · Narrowing and unions
Type predicate
A user-defined guard that teaches TypeScript how a function narrows its argument.
Syntax
function isUser(v: unknown): v is UserExample
Example
type User = { id: string };
function isUser(value: unknown): value is User {
return typeof value === "object" && value !== null && "id" in value;
}
console.log(isUser({ id: "u1" }));More in this group
Learn this in the course
Reference pages are the quick answer. The course explains the why, shows the full example and ends with a challenge.