asrt

A small library to verify preconditions and postconditions.

Usage no npm install needed!

<script type="module">
  import asrt from 'https://cdn.skypack.dev/asrt';
</script>

README

asrt

A small library to verify preconditions and postconditions.

Usage

import {always} from 'core';

function add(x, y) {
    always(typeof x === 'number', "Argument 'x' has to be a number.");
    always(typeof y === 'number', "Argument 'y' has to be a number.");
    return x + y;
}

always() and assert() functions throw an AssertionError if the condition is false:

always(1 > 0); // ok
always(1 < 0); // throws AssertionError

never() does the same but in reverse:

never(1 > 0); // throws AssertionError
never(1 < 0); // ok

TypeScript

Asrt functions always() and assert() are typed to assert that the condition you pass them are true, which gives you certainty that your variable is of a given type at runtime.

export declare function always(condition: boolean, ...messages: ReadonlyArray<string>): asserts condition;
const x: unknown = someUntypedFunction();
always(typeof x === 'string');
const y = x.toUpperCase(); // TypeScript knows that x must be a string, your IDE can suggest toUpperCase() method