TypeScript

invariant() — Always-On Assertion

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Throw if a condition is false, with TypeScript narrowing the type afterwards. Replaces ad-hoc `if (!x) throw` ladders and gives you type-safe guards in one line.
TypeScript
Raw
export function invariant(condition: unknown, message: string | (() => string)): asserts condition {
  if (condition) return;
  const msg = typeof message === 'function' ? message() : message;
  throw new Error(`Invariant failed: ${msg}`);
}

function processUser(u: { id: number; email: string | null }) {
  invariant(u.email, 'user must have an email');
  // u.email is narrowed to `string` here — TS understands `asserts condition`
  sendEmail(u.email);
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.