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 User

Example

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

Assertion function Discriminated union Exhaustive switch in operator instanceof guard Non-null assertion Type assertion typeof guard

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.

Open the course