ts-invariant: TypeScript Assertions

0.10.3 · active · verified Sun Apr 19

ts-invariant is a TypeScript-first implementation of the widely used `invariant(condition, message)` assertion pattern. It's designed for validating preconditions and ensuring consistent program state, primarily in development builds. The current stable version is 0.10.3. Actively maintained as part of the Apollo GraphQL ecosystem, its release cadence is tied to broader project needs rather than a fixed schedule. Key differentiators include robust TypeScript typing for compile-time safety, extended logging capabilities (`invariant.log`, `invariant.warn`, `invariant.error`), and configurable verbosity via `setVerbosity`. A significant feature is its compatibility with bundler plugins (like `rollup-plugin-invariant`, though that plugin is now archived), which can strip assertion messages from production bundles to reduce file size, making it a performance-conscious choice for assertions.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates importing `invariant`, `setVerbosity`, and `InvariantError`, showing basic assertion, logging levels, and the effect of verbosity settings. It also highlights `process.env.NODE_ENV` behavior.

import { invariant, setVerbosity, InvariantError } from "ts-invariant";

// Default verbosity is 'log'
console.log("--- Default verbosity (log) ---");

// This will throw an InvariantError if the condition is false
try {
  const username: string | undefined = undefined;
  invariant(username, "Username must be defined and not empty.");
} catch (e) {
  if (e instanceof InvariantError) {
    console.error("Invariant failed as expected:", e.message);
  } else {
    console.error("Unexpected error:", e);
  }
}

// Log a warning message
invariant.warn("This is a warning message that will be displayed by default.");

// Change verbosity to suppress log messages
console.log("\n--- Setting verbosity to 'warn' ---");
setVerbosity("warn");

// This log will now be suppressed and not appear in the console
invariant.log("This log message should be suppressed at 'warn' verbosity.");

// This warning will still show
invariant.warn("This warning message should still show at 'warn' verbosity.");

// This error will still show
invariant.error("This error message should still show at 'warn' verbosity.");

// Revert verbosity to default for further operations or tests
setVerbosity("log");
console.log("\n--- Verbosity reverted to 'log' ---");

// Example of how invariants are often handled for production builds
// In production, bundlers might strip these messages for smaller bundles.
if (process.env.NODE_ENV === 'production') {
  // In a real production build, this invariant message might be stripped.
  invariant(false, "This message is for dev only. Production build will strip it if configured.");
} else {
  invariant.log("In development, invariant messages (like the one above) are usually active for debugging.");
}

view raw JSON →