Package Exports
- @santi100/assertion-lib
- @santi100/assertion-lib/cjs
- @santi100/assertion-lib/cjs/index.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
*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, { expected, actual, operator }?: AssertOptionalParams): void;Asserts thatconditionis 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. (deprecated as per 1.0.8) Asserts that the type offunction assertType(val: unknown, expectedType: Type): void;valisexpectedType. Throws anAssertionErrorotherwise.Parameter Type Description valunknownAn expression whose type is to be asserted. expectedTypeTypeThe type to assert. DEPRECATED: Use assertTypeOfinstead.function assertTypeOf(arg: any, expectedType: Type, name: string): void;(since 1.0.6,nameis optional since 1.0.8) Asserts that the type ofargisexpectedType. 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(arg: any, name: string, choices: any[]): void;(since 1.0.6, type param bound tochoicesadded in 1.0.8) Assertsargis one ofchoices. Throws aTypeErrorotherwise.Parameter Type Description arganyThe value that's expected to be included within choices.namestringAn expression name to be put in the TypeError's message.choicesany[]An array containing the posible values argshould have in order for an error not to be thrown.shallow?(since 1.0.8)booleanorundefinedWhether or not to use shallow equality (default deep equality is powered by @santi100/equal-lib😉).function assertInteger(arg: number, name: string): void;(since 1.0.6) Assertsargis an integer. Throws aTypeErrorotherwise.function assertMin(arg: any, name: string, min: any): void;(since 1.0.6) Assertsargis bigger or equal thanmin. Throws aTypeErrorotherwise.function assertMax(arg: any, name: string, max: any): void;(since 1.0.6) Assertsargis smaller or equal thanmax. Throws aTypeErrorotherwise.function assertRange(arg: any, name: string, min: any, max: any): void;(since 1.0.6) Assertsargis betweenmin + 1andmax + 1(inclusive). Throws aTypeError(RangeErrorsince 1.0.7) otherwise.function assertArray(arg: any, name?: string): void;(since 1.0.7) Assertsargis an Array. Throws aTypeErrorotherwise.
Usage example
import {
assert,
assertType,
assertTypeOf,
assertOneOf,
assertInteger,
assertMin,
assertMax,
AssertionError,
Type
} from '@santi100/assertion-lib'; // ESM
const {
assert,
assertType,
assertTypeOf,
assertOneOf,
assertInteger,
assertMin,
assertMax,
AssertionError,
Type
} = require('@santi100/assertion-lib'); // CJS
function sum(a: number, b: number) {
assertType(a, 'number');
assertType(b, 'number');
return a + b;
}
function divide(a: number, b: number) {
assertType(a, 'number');
assertType(b, 'number');
assert(b !== 0, { expected: 'non-zero number', actual: b, operator: '!==' });
return a / b;
}
function getGreeting(name: string, language: string) {
assertType(name, 'string');
assertOneOf(language, 'language', ['en', 'es']);
const greetings = {
en: 'Hello',
es: 'Hola'
};
return `${greetings[language]}, ${name}!`;
}
function getFactorial(n: number) {
assertType(n, 'number');
assertInteger(n, 'n');
assertMin(n, 'n', 0);
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
try {
// Example of a failed assertion:
assert(1 === 2);
} catch (error) {
if (error instanceof AssertionError) {
console.log('Expected:', error.expected); // 2
console.log('Actual:', error.actual); // 1
console.log('Operator:', error.operator); // '==='
}
}
try {
// Example of a type assertion:
assertType('hello', 'number');
} catch (error) {
if (error instanceof AssertionError) {
console.log(error.message); // 'Assertion failed! Expected number. Got string when using operator typeof.'
}
}
try {
// Example of an assertion with custom error parameters:
divide(10, 0);
} catch (error) {
if (error instanceof AssertionError) {
console.log(error.message); // 'Assertion failed! Expected non-zero number. Got 0 when using operator !==.'
}
}
try {
// Example of an assertion with one of:
getGreeting('John', 'fr');
} catch (error) {
if (error instanceof TypeError) {
console.log(error.message); // '"language" must be one of "en, es". Got "fr" of type "string".'
}
}
try {
// Example of an integer assertion:
getFactorial(3.5);
} catch (error) {
if (error instanceof TypeError) {
console.log(error.message); // '"n" must be an integer. Got "3.5" of type "number".'
}
}
try {
// Example of a minimum assertion:
getFactorial(-1);
} catch (error) {
if (error instanceof TypeError) {
console.log(error.message); // '"n" must be bigger than 0. Got "-1" of type "number".'
}
}
try {
// Example of a maximum assertion:
assertMax(10, 'n', 5);
} catch (error) {
if (error instanceof TypeError) {
console.log(error.message); // '"n" must be smaller than 5. Got "10" of type "number".'
}
}