Assertion Functions
In this page:
Basic Assertions
An assertion function uses the special asserts condition return type to tell TypeScript that, once the function returns normally, that condition is now guaranteed to be true for the rest of the code.
Example: Basic Assertions
function assert(condition: boolean, msg: string): asserts condition {
if (!condition) throw new Error(msg);
}
const x: number | undefined = 5;
assert(x !== undefined, "x must be defined");
console.log(x + 1);
Asserting Object Types
An assertion function can also use the form asserts value is Type to narrow an unknown value down to a specific interface — if the function doesn't throw, TypeScript trusts the value now has that shape.
Example: Asserting Object Types
interface User {
name: string;
}
function assertIsUser(value: any): asserts value is User {
if (typeof value?.name !== "string") throw new Error("Not a user");
}
const data: any = { name: "Ravi" };
assertIsUser(data);
console.log(data.name);
Assertion Functions and null
Assertions shine whenever a value absolutely must exist before code can safely continue — required configuration that must be loaded, a DOM element expected to be on the page, or an application invariant that must hold.
Example: Assertion Functions and null
function assertExists<T>(value: T | null, msg: string): asserts value is T {
if (value === null) throw new Error(msg);
}
const config: { key: string } | null = { key: "value" };
assertExists(config, "config must be loaded");
console.log(config.key);
Assertions for Invariants
Assertions can enforce rules that must remain true throughout an application's logic — if an invariant is violated, throwing immediately stops execution right at the point where things went wrong, rather than letting a bad value propagate.
Example: Assertions for Invariants
function assertPositive(n: number): asserts n is number {
if (n <= 0) throw new Error("value must be positive, got " + n);
}
const balance = 10;
assertPositive(balance);
console.log("Balance ok:", balance);
Assertions vs Boolean Guards
A boolean type guard returns true or false and leaves the caller to decide what to do next, while an assertion function throws when its condition fails and silently narrows the type for the code that follows if it doesn't.
Example: Assertions vs Boolean Guards
function isPositive(n: number): boolean {
return n > 0;
}
function assertPositive(n: number): asserts n is number {
if (n <= 0) throw new Error("must be positive");
}
console.log(isPositive(-1));
assertPositive(5);
console.log("passed assertion");
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- TypeScript Advanced Types
- Mapped Types
- Conditional Types
- Custom Type Guards
- Assertion Functions
- Control Flow Analysis
- Exhaustiveness Checking
- Satisfies Operator
- Template Literal Types
- Utility Types - Partial
- Utility Types - Required
- Utility Types - Readonly
- Utility Types - Pick
- Utility Types - Omit
- Utility Types - Record
- Utility Types - Exclude and Extract
- Utility Types - NonNullable
- Utility Types - ReturnType
- Utility Types - Parameters
- TypeScript 5 Updates