module-or-throw #
Ready to publish.
Runtime assertions that pass the value through or throw.
Each helper narrows the static type when the runtime check passes,
and throws an Error describing the offending value when the check fails.
Use these wherever the non-null assertion operator (!) would otherwise be reached for:
the runtime check turns a silent type lie into a loud,
debuggable failure.
Helpers #
Boolean shape #
| Function | Throws when |
|---|---|
| `nonNullishOrThrow` | value is `null` or `undefined` |
| `truthyOrThrow` | value is falsy (`false`, `0`, `0n`, `''`, `null`, `undefined`, or `NaN`) |
| `falsyOrThrow` | value is truthy |
Container size #
| Function | Throws when |
|---|---|
| `emptyOrThrow` | value lacks a recognized size shape, or has nonzero size |
| `nonemptyOrThrow` | value lacks a recognized size shape, or has zero size |
Recognized size shapes:
strings,
arrays,
Set,
Map,
plain objects.
WeakSet and WeakMap are intentionally rejected (no enumerable size).
Bare iterables and async iterables are rejected (sizing requires consumption).
Iterable protocols #
| Function | Throws when |
|---|---|
| `iterableOrThrow` | value does not implement the sync-iterable protocol |
| `asyncIterableOrThrow` | value does not implement the async-iterable protocol |
| `maybeAsyncIterableOrThrow` | value implements neither protocol |
Strings count as sync-iterable.
Objects must have Symbol.iterator or Symbol.asyncIterator to pass.
Container instances #
| Function | Throws when |
|---|---|
| `arrayOrThrow` | `Array.isArray(value)` is `false` |
| `setOrThrow` | value is not `instanceof Set` |
| `mapOrThrow` | value is not `instanceof Map` |
| `weakSetOrThrow` | value is not `instanceof WeakSet` |
| `weakMapOrThrow` | value is not `instanceof WeakMap` |
Standard built-ins #
| Function | Throws when |
|---|---|
| `promiseOrThrow` | value is not `instanceof Promise` |
| `dateOrThrow` | value is not `instanceof Date` |
| `regExpOrThrow` | value is not `instanceof RegExp` |
| `errorOrThrow` | `Error.isError(value)` is `false` |
dateOrThrow does not check date validity (invalid dates still pass).
promiseOrThrow rejects thenables.
errorOrThrow accepts genuine errors from any realm and rejects error-shaped plain objects.
typeof primitives #
| Function | Throws when |
|---|---|
| `stringOrThrow` | `typeof value !== 'string'` |
| `numberOrThrow` | `typeof value !== 'number'` (accepts `NaN` and `Infinity`) |
| `bigintOrThrow` | `typeof value !== 'bigint'` |
| `booleanOrThrow` | `typeof value !== 'boolean'` |
| `symbolOrThrow` | `typeof value !== 'symbol'` |
| `functionOrThrow` | `typeof value !== 'function'` |
| `objectOrThrow` | `typeof value !== 'object'` or `value === null` |
Boxed-primitive wrappers (new String(...),
new Number(...),
etc.) are intentionally rejected.
Numeric union #
| Function | Throws when |
|---|---|
| `numericOrThrow` | value is neither `number` nor `bigint` |
numericOrThrow corresponds to the t numeric/ category in module-es.
Custom predicates #
satisfiesOrThrow({ value, predicate? })(candidate)throws when the synchronous satisfaction check fails.satisfiesOrThrowAsync({ value, predicate? })(candidate)throws when the async-capable satisfaction check fails.
When predicate is omitted,
both helpers use Object.is(candidate, value).
Default equality narrows the successful return type to the intersection of the candidate type
and the configured value type.
When predicate is present,
it receives one object parameter:
{ candidate, value }.
A true result returns candidate unchanged.
A false result throws an Error.
Predicates may also throw their own error.
That is a supported use case:
the helper does not wrap or replace predicate-thrown errors,
so predicates can provide domain-specific diagnostics.
Predicates must return literal booleans.
The synchronous helper rejects Promise-returning predicates at runtime and points callers to
satisfiesOrThrowAsync.
The async helper accepts boolean or Promise<boolean>,
then rejects resolved non-boolean values.
Async predicate rejections also propagate unchanged.
Custom predicates deliberately return the candidate type as-is because predicates can be fuzzy:
for example,
a case-insensitive predicate can accept 'READY' for configured value 'ready',
so typing the result as literal 'ready' would lie about the runtime value.
Usage #
import {
arrayOrThrow,
nonNullishOrThrow,
stringOrThrow,
} from '@monochromatic-dev/module-or-throw';
const el = nonNullishOrThrow(document.querySelector('.target',),);
// el is Element (was Element | null)
const text = stringOrThrow(el.textContent,);
// text is string (was string | null)
const tokens = arrayOrThrow(text.match(/\w+/g,),);
// tokens is readonly unknown[] (was RegExpMatchArray | null)
Custom predicate usage #
import {
satisfiesOrThrow,
satisfiesOrThrowAsync,
} from '@monochromatic-dev/module-or-throw';
declare const rawStatus: unknown;
declare const expectedChecksum: string;
declare const filePath: string;
declare function checksumMatches(parameters: {
readonly candidate: unknown;
readonly value: string;
}): Promise<boolean>;
const exactReady = satisfiesOrThrow({ value: 'ready' as const, })(rawStatus,);
// exactReady is typed as 'ready' when rawStatus was unknown.
const readyish = satisfiesOrThrow({
value: 'ready',
predicate: ({ candidate, value, }) =>
((typeof candidate) === 'string')
&& (candidate.toLowerCase() === value),
})('READY',);
// readyish is the original candidate, 'READY'.
const stored = await satisfiesOrThrowAsync({
value: expectedChecksum,
predicate: async ({ candidate, value, }) => await checksumMatches({
candidate,
value,
},),
})(filePath,);
// stored is the original candidate, filePath.
Types #
import type {
ExtractOrUnknown,
Falsy,
} from '@monochromatic-dev/module-or-throw';
Falsy: union offalse | 0 | 0n | '' | null | undefined.NaNis falsy at runtime but cannot be represented as a literal type.ExtractOrUnknown<T, U>: variant ofExtract<T, U>that returnsUwhenTisunknown, instead of collapsing tonever. Used internally by everyExtract-based narrowing helper sounknowninputs (e.g. parsed JSON) narrow correctly.SatisfiesOrThrowPredicateParameters<Candidate, Value>: object passed into custom predicates.SatisfiesOrThrowPredicate<Value, Candidate = unknown>: synchronous predicate type returningboolean.SatisfiesOrThrowAsyncPredicate<Value, Candidate = unknown>: async-capable predicate type returningbooleanorPromise<boolean>.
NaN caveat #
NaN is falsy at runtime but cannot be represented as a TypeScript literal type.
truthyOrThrow(NaN,) throws at runtime,
but TypeScript cannot statically exclude NaN from a number parameter,
so the returned type is the same number.
numberOrThrow accepts NaN:
it is a number-typed value.
Callers that need a NaN-narrowed type must use Number.isNaN separately.
Design decisions #
- **Source-only.
** The package has no build step;
consumers import directly from
src/index.ts. - **Direct named exports.
** No
$aliasing. Consumers writeimport { nonNullishOrThrow }and call the function by its real name. - **One file per helper.
** Each helper owns a sibling file;
index.tsis a pure re-export barrel. - **Family convention.
** Every helper in this package uses the
<predicate>OrThrowsuffix so the throw semantics are explicit at every call site, even when the import line is folded or out of view. - **
ExtractOrUnknownoverExtract. ** PlainExtract<unknown, X>evaluates tonever, silently breaking the most common call shape (a value typedunknownfrom parsed JSON or a fetched payload). Every narrowing helper usesExtractOrUnknowninstead. - **Skipped categories.
** Value-range refinements (
positiveOrThrow,finiteOrThrow,integerOrThrow) are intentionally out of scope; add them when a call site needs them.