Registry / testing / ts-invariant

ts-invariant

JSON →
library0.10.3jsnpmunverified

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.

npm install ts-invariant
INSTALL
IMPORT
SIG · TS-INVARIANT
T
ts-invariant
testingjavascriptv0.10.3
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

invariant
import { invariant } from 'ts-invariant';
import invariant from 'ts-invariant';
The core `invariant` function is a named export, not a default export.
setVerbosity
import { setVerbosity } from 'ts-invariant';
const { setVerbosity } = require('ts-invariant');
CommonJS `require` for ESM-first packages can lead to module resolution issues, especially in newer Node.js environments or with strict bundler configurations.
InvariantError
import { InvariantError } from 'ts-invariant';
Used for `instanceof` checks when catching errors thrown by `invariant`.

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."); }
Debug
Known issues
gotchaError messages from `invariant` and its logging methods (`invariant.log`, `invariant.warn`, `invariant.error`) can be stripped from production bundles. This is typically done by bundler plugins (e.g., `rollup-plugin-invariant`, though now archived). While beneficial for bundle size, it means production builds might not show detailed assertion messages, making debugging production issues challenging if unaware.
fix
Ensure `process.env.NODE_ENV` is correctly set to 'development' during development builds to retain messages. For production debugging, either temporarily disable stripping or rely on stack traces and code context.
affects: >=0.1.0
gotcha`ts-invariant` often relies on `process.env.NODE_ENV` to determine its behavior, especially regarding message stripping. If `process.env` is not properly polyfilled or replaced by a bundler in non-Node.js environments (like browsers), it might lead to unexpected runtime behavior or errors.
fix
When bundling for browsers, ensure your bundler (e.g., Webpack, Rollup, Vite) correctly defines or polyfills `process.env.NODE_ENV`. For Webpack, use `DefinePlugin`; for Rollup, use `@rollup/plugin-replace`.
affects: >=0.1.0
breakingThe `rollup-plugin-invariant` package, which was commonly used to strip `ts-invariant` messages in production, has been moved to an archived directory by the Apollo GraphQL team. While its functionality might still work, it indicates a lack of active maintenance and potential for future compatibility issues with newer Rollup versions or other tooling.
fix
Consider migrating to alternative bundler plugins or custom configurations that achieve similar dead-code elimination if you rely on stripping invariant messages. Verify continued compatibility if you remain on `rollup-plugin-invariant`.
affects: >=0.10.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'env')
This error occurs when `process` is accessed in a browser environment, and it has not been properly polyfilled or defined by the bundler.
fix
Configure your bundler to provide a `process.env` polyfill or replacement. For Webpack, use `new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) });`. For Rollup, use `@rollup/plugin-replace`.
Invariant Violation: Username must be defined and not empty.
This is the expected runtime error when an `invariant` condition evaluates to false. If this occurs in a production environment where messages are typically stripped, it implies that the stripping mechanism is not active or correctly configured.
fix
During development, this is a signal to fix the underlying condition. In production, if messages are not stripped, verify your bundler's configuration for `process.env.NODE_ENV` and the invariant stripping plugin.
TypeError: (0, ts_invariant__WEBPACK_IMPORTED_MODULE_0__.invariant) is not a function
This usually indicates an incorrect import statement, where `invariant` is attempted to be imported as a default export rather than a named export, especially in CommonJS contexts or misconfigured ESM.
fix
Change your import statement from `import invariant from 'ts-invariant';` to `import { invariant } from 'ts-invariant';`. If using CommonJS, ensure transpilation or use `const { invariant } = require('ts-invariant');` (though ESM is preferred).
Upgrade
Version history
0.10.3latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
4 hits · last 30 days
node
4
Resources
ts-invariant — npm install ts-invariant · libregistry