TypeScript · Narrowing and unions

Assertion function

A function that throws when a condition fails and therefore narrows for the caller.

Syntax
asserts value is User

Example

Example
type User = { id: string };
function assertUser(value: unknown): asserts value is User {
  if (!value || typeof value !== "object" || !("id" in value)) throw new Error("Not a user");
}
const data: unknown = { id: "u1" };
assertUser(data);
console.log(data.id);

More in this group

Discriminated union Exhaustive switch in operator instanceof guard Non-null assertion Type assertion Type predicate 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