What is ts-invariant?
The ts-invariant package provides utility functions for asserting invariants within TypeScript applications. It is designed to throw errors when certain conditions are not met, which can be useful for catching programming errors and enforcing certain constraints at runtime.
What are ts-invariant's main functionalities?
Invariant
The invariant function is used to assert that a condition is true. If the condition is false, it will throw an error with the provided error message.
import { invariant } from 'ts-invariant';
invariant(condition, 'Expected condition to be true');
Invariant.warn
The invariant.warn function is used to log a warning message to the console. It does not throw an error.
import { invariant } from 'ts-invariant';
invariant.warn('This is a warning message');
Invariant.error
The invariant.error function is used to log an error message to the console. It does not throw an error.
import { invariant } from 'ts-invariant';
invariant.error('This is an error message');
Other packages similar to ts-invariant
assert
The 'assert' module is a built-in Node.js package that provides a simple set of assertion tests. It is similar to ts-invariant in that it is used to test invariants, but it is not specifically tailored for TypeScript and does not provide the same logging capabilities.
chai
Chai is a BDD/TDD assertion library for Node.js and the browser that can be paired with any JavaScript testing framework. It offers a richer set of assertions than ts-invariant, including property checks, deep equality, and chainable assertions, making it more suitable for complex testing scenarios.
prop-types
Prop-types is a library for runtime type checking for React props and similar objects. While it serves a different purpose than ts-invariant, it also provides a way to enforce type constraints at runtime, which is a form of invariant checking.
ts-invariant
TypeScript implementation of
invariant(condition, message)
.
Supports invariant.log
, invariant.warn
, and invariant.error
, which
wrap console
methods of the same name, and may be stripped in production
by rollup-plugin-invariant
.
The verbosity of these methods can be globally reconfigured using the
setVerbosity
function:
import { setVerbosity } from "ts-invariant";
setVerbosity("log");
setVerbosity("warn");
setVerbosity("error");
setVerbosity("silent");