Skip to content

yummies/assert

Description

Runtime assertions for invariants, narrowing, and exhaustiveness. Helpers throw AssertionError with an optional message (string or MaybeFn) so failing fast stays explicit without a heavy assertion library. Use assert.ok, assert.string, assert.defined, assert.fail, and the rest on the namespace export from the package entry.

Usage

ts
import { assert } from "yummies/assert";

assert.ok(user.id, "user id is required");
assert.defined(maybeName);
assert.string(raw);

assert.AssertionError

Error thrown by assertion helpers in this module.

assert.ok()

Throws when condition is falsy; narrows the type when it is truthy.

Example:

ts
assert.ok(user.id, "user id is required");

assert.invariant

Same as ok; common alias for internal invariants (e.g. after optional checks).

assert.defined()

Throws when the value is null or undefined; otherwise narrows away nullish.

Example:

ts
assert.defined(maybeName, "name must be present");

assert.notNull()

Throws when the value is null; allows undefined unless combined with other checks.

assert.notUndefined()

Throws when the value is undefined.

assert.string()

Throws when value is not a string (primitive or String object); uses typeGuard.isString.

assert.number()

Throws when value is not a finite non-NaN number; uses typeGuard.isNumber.

assert.boolean()

Throws when value is not a boolean; uses typeGuard.isBoolean.

assert.symbol()

Throws when value is not a symbol; uses typeGuard.isSymbol.

assert.fail()

Always throws; use for branches that must be impossible or as a typed “abort”.

Example:

ts
function parse(kind: "a" | "b") {
  if (kind === "a") return 1;
  if (kind === "b") return 2;
  assert.fail("unreachable");
}

assert.unreachable()

Exhaustiveness helper: call with a never value when all union cases are handled.

assert.instanceOf()

Throws when value is not an instance of ctor.

Example:

ts
assert.instanceOf(el, HTMLElement, "expected a DOM element");

Released under the MIT License.