TypeScript · Narrowing and unions
Assertion function
A function that throws when a condition fails and therefore narrows for the caller.
Syntax
asserts value is UserExample
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
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.