Assertion functions are functions that throw if a condition is not met, and narrow the type of their argument after the call. asserts x is Type narrows x for all code after the assertion call. asserts condition narrows based on the condition. Unlike type predicates (returns boolean), assertion functions return void — they narrow the scope unconditionally because if they do not throw, the assertion passed. Essential for invariant enforcement at domain boundaries.
Using assertDefined to handle nullable values ergonomically.
data as User is a lie you tell the compiler. assertIsUser(data): asserts data is User proves it at runtime and then the type is accurate. Use assertions at untrusted boundaries (API responses, DB results).
assertOrderIsActive(order) encodes both the runtime check and the type narrowing. After calling it, the order is typed as ActiveOrder — methods that only exist on active orders become available.
Calling assertDefined(value) once narrows value from T | null to T for the entire remaining scope. No need for value! non-null assertions or repeated if (value === null) checks.
Sign in to share your feedback and join the discussion.