Careeroza
Assertion Functions
asserts value is T
An assertion function throws if a condition is false. Its return type asserts x is T (or asserts condition) tells TypeScript that, after the call, the value has been narrowed. No if needed.
Example
function assert(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(message);
}
function assertIsString(x: unknown, name: string): asserts x is string {
if (typeof x !== "string") throw new TypeError(name + " must be a string");
}
function applyCoupon(code: unknown, cartTotal: number | null): string {
assertIsString(code, "code");
assert(cartTotal !== null, "Cart is empty");
return code.toUpperCase() + " applied on Rs. " + cartTotal.toFixed(0);
}
console.log(applyCoupon("save10", 1200));
try {
applyCoupon(42, 1200);
} catch (e) {
console.log((e as Error).message);
}Output
SAVE10 applied on Rs. 1200 code must be a string
Rule
Note: An assertion function must be declared with an explicit type (a function declaration or a typed const). Node.js has a built-in one: import assert from "node:assert".