Package Exports
- @santi100/assertion-lib
- @santi100/assertion-lib/cjs
- @santi100/assertion-lib/cjs/array
- @santi100/assertion-lib/cjs/array.js
- @santi100/assertion-lib/cjs/index.js
- @santi100/assertion-lib/cjs/instance-of
- @santi100/assertion-lib/cjs/instance-of.js
- @santi100/assertion-lib/cjs/integer
- @santi100/assertion-lib/cjs/integer.js
- @santi100/assertion-lib/cjs/max
- @santi100/assertion-lib/cjs/max.js
- @santi100/assertion-lib/cjs/min
- @santi100/assertion-lib/cjs/min.js
- @santi100/assertion-lib/cjs/positive
- @santi100/assertion-lib/cjs/positive.js
- @santi100/assertion-lib/cjs/range
- @santi100/assertion-lib/cjs/range.js
- @santi100/assertion-lib/cjs/type-of
- @santi100/assertion-lib/cjs/type-of.js
- @santi100/assertion-lib/index.mjs
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@santi100/assertion-lib) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Santi's Assertion Library
- 🚀 Lightweight and fast^
- 👴 ES3-compliant*
- 💻 Portable between the browser and Node.js
- 📘 Comes with built-in TypeScript definitions
- 📑 Split into a lot of modules (under
cjs/) so you get to choose what you want - 🎨 Includes a wide array of assertion functions
- 💪 Very customizable (you get to choose comparison logic, name displayed on error, et cetera)
*Hasn't been tested in an actual ES3 environment. Feel free to open an issue or pull request if you find any non-ES3 thing. See "Contribute" for instructions on how to do so.
^The source code is about 2 kilobytes.
What's this?
This is an assertion library for types and conditions. It's designed to be lightweight and portable between the browser and Node.js.
Contribute
Wanna contribute? File an issue or pull request! Make sure you follow the contribution Code of Conduct.
Installation
- Via NPM:
npm install @santi100/assertion-lib - Via Yarn:
yarn add @santi100/assertion-lib - Via PNPM:
pnpm install @santi100/assertion-lib
API
function assert(condition: boolean, params?: AssertOptionalParams): void;Asserts that
conditionis truthy. Throws anAssertionErrorotherwise.Parameter Type Description conditionbooleanThe condition to assert. assertParamsAssertOptionalParams<E, A>AssertionErroroptions.assertParams.expectedEExpected value for the assertion. assertParams.actualAReceived value for the assertion. assertParams.operatorstringOptional operator used for the assertion. function assertTypeOf(arg: any, expectedType: Type, name: string): void;(since 1.0.6,nameis optional since 1.0.8)Asserts that the type of
argisexpectedType. Throws aTypeErrorotherwise.Parameter Type Description arganyAn expression whose type is to be asserted. expectedTypeTypeThe expected type. namestringAn optional expression name to be put in the TypeError's message. Defaults to "arg".function assertOneOf<T = unknown>(arg: any, name: string, choices: any[]): void;(since 1.0.6, type param bound tochoicesadded in 1.0.8)Asserts
argis one ofchoices, usingcomparatorto compareargagainst each choice. Throws aTypeErrorotherwise.WARNING: Since v2, the
shallowargument is no longer valid -- it has been replaced withcomparator.This is done so you can use this library without the need to install
@santi100/equal-lib, whilst also adding flexibility to use custom comparison logic or the deep equality library of your choice.Parameter Type Description arganyThe value that's expected to be included within choices.namestringAn expression name to be put in the TypeError's message.choicesT[]An array containing the posible values argshould have in order for an error not to be thrown.comparator?(since 2.0.0)(a: unknown, b: T) => booleanorundefinedA custom comparator to add, for instance, deep equality! function assertInteger(arg: number, name: string): void;(since 1.0.6)Asserts
argis an integer. Throws aTypeErrorotherwise.function assertMin(arg: any, name: string, min: any): void;(since 1.0.6)Asserts
argis bigger or equal thanmin. Throws aTypeErrorotherwise.function assertMax(arg: any, name: string, max: any): void;(since 1.0.6)Asserts
argis smaller or equal thanmax. Throws aTypeErrorotherwise.function assertRange(arg: any, name: string, min: any, max: any): void;(since 1.0.6)Asserts
argis NEITHER smaller thanminNOR bigger thanmax. Throws aTypeError(RangeErrorsince 1.0.7) otherwise.function assertArray(arg: any, name?: string): void;(since 1.0.7)Asserts
argis an Array. Throws aTypeErrorotherwise.function assertDefined<T = unknown>(element: T): void;(since 2.0.1)Checks if a given element is defined, i.e., not null or undefined. If the element is null or undefined, the function throws a TypeError with a message indicating the name of the element.
Parameter Type Description Optional? elementTThe value to be checked for being defined. No Throws an error if the element is null or undefined.
Example:
assertDefined(5); // No error thrown assertDefined(null); // Throws TypeError: 'element' is null assertDefined(undefined); // Throws TypeError: 'element' is undefined assertDefined('hello'); // No error thrown
function assertMatch(str: string, re: RegExp, name?: string): void;(since 2.0.1)Asserts
strmatchesre. Throws aTypeErrorotherwise.Parameter Type Description Optional? strstringThe string to match against re.No reRegExpThe regular expression to match stragainst.No namestringThe displayed name in the TypeErrorthrown ifstrdoes not matchre.Defaults to str.No
Usage example
// Import the assertion functions
// CJS
const assert = require('@santi100/assertion-lib/cjs/assert');
const assertTypeOf = require('@santi100/assertion-lib/cjs/type-of');
const assertOneOf = require('@santi100/assertion-lib/cjs/one-of');
const assertInteger = require('@santi100/assertion-lib/cjs/integer');
const assertMin = require('@santi100/assertion-lib/cjs/min');
const assertMax = require('@santi100/assertion-lib/cjs/max');
const assertRange = require('@santi100/assertion-lib/cjs/range');
const assertArray = require('@santi100/assertion-lib/cjs/array');
const assertDefined = require('@santi100/assertion-lib/cjs/defined');
const assertMatch = require('@santi100/assertion-lib/cjs/match');
// TypeScript
import assert = require('@santi100/assertion-lib/cjs/assert');
import assertTypeOf = require('@santi100/assertion-lib/cjs/type-of');
import assertOneOf = require('@santi100/assertion-lib/cjs/one-of');
import assertInteger = require('@santi100/assertion-lib/cjs/integer');
import assertMin = require('@santi100/assertion-lib/cjs/min');
import assertMax = require('@santi100/assertion-lib/cjs/max');
import assertRange = require('@santi100/assertion-lib/cjs/range');
import assertArray = require('@santi100/assertion-lib/cjs/array');
import assertDefined = require('@santi100/assertion-lib/cjs/defined');
import assertMatch = require('@santi100/assertion-lib/cjs/match');
// ESM
import assert from '@santi100/assertion-lib/cjs/assert';
import assertTypeOf from '@santi100/assertion-lib/cjs/type-of';
import assertOneOf from '@santi100/assertion-lib/cjs/one-of';
import assertInteger from '@santi100/assertion-lib/cjs/integer';
import assertMin from '@santi100/assertion-lib/cjs/min';
import assertMax from '@santi100/assertion-lib/cjs/max';
import assertRange from '@santi100/assertion-lib/cjs/range';
import assertArray from '@santi100/assertion-lib/cjs/array';
import assertDefined from '@santi100/assertion-lib/cjs/defined';
import assertMatch from '@santi100/assertion-lib/cjs/match';
// Or import it all
import * as assertionLib from '@santi100/assertion-lib'; // ESM or TypeScript
const assertionLib = require('@santi100/assertion-lib'); // CJS
// Usage example for assert
function divide(a, b) {
assert(typeof a === 'number' && typeof b === 'number', {
message: 'Arguments must be numbers.'
});
assert(b !== 0, {
message: 'Cannot divide by zero.',
expected: 'Non-zero value',
actual: b
});
return a / b;
}
// Usage example for assertTypeOf
function greet(name) {
assertTypeOf(name, 'string', 'name');
return `Hello, ${name}!`;
}
// Usage example for assertOneOf
function checkOperator(operator) {
assertOneOf(operator, 'operator', ['+', '-', '*', '/'], (a, b) => a.trim() === b.trim());
return `Valid operator: ${operator}`;
}
// Usage example for assertInteger
function multiplyByTwo(num) {
assertInteger(num, 'num');
return num * 2;
}
// Usage example for assertMin
function greetWithMinimumLength(name) {
assertMin(name.length, 'name', 3);
return `Hello, ${name}!`;
}
// Usage example for assertMax
function greetWithMaximumLength(name) {
assertMax(name.length, 'name', 10);
return `Hello, ${name}!`;
}
// Usage example for assertRange
function greetWithPreferredLength(name) {
assertRange(name.length, 'name', 5, 8);
return `Hello, ${name}!`;
}
// Usage example for assertArray
function sumNumbers(numbers) {
assertArray(numbers, 'numbers');
return numbers.reduce((sum, num) => sum + num, 0);
}
// Usage example for assertDefined
function greetIfDefined(name) {
assertDefined(name, 'name');
return `Hello, ${name}!`;
}
// Usage example for assertMatch
function isValidEmail(email) {
assertMatch(email, /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/i, 'email');
return true;
}