@metreeca/core - v0.10.0
    Preparing search index...

    Module index

    Core types, guards, and utilities.

    Bridges the gap between TypeScript's static type system and untrusted runtime data. Every guard returns a boolean and narrows its argument on success, so validation and type inference collapse into a single call at API boundaries, deserialisation sites, and other trust-crossing points. Companion utilities work along the same lines, deferring values to first use, binding a value to a mapper of its own with or without a tolerance for its absence, and reporting failures where a statement isn't allowed.

    isNullable, isOptional and isDefined settle how the empty values are treated at a given boundary: both markers admitted, undefined alone admitted, or presence required. A type guard constrains whatever each of them accepts beyond emptiness, required by the first two and optional for the last, and the results narrow through the matching Nullable, Optional and Defined type operators.

    isNullable(null, isString); // true (undefined and null both accepted)
    isOptional(undefined, isString); // true (undefined accepted, null rejected)
    isDefined("value"); // true
    isDefined(null); // true (only undefined is rejected)
    isDefined(value, isString); // presence and type in a single check

    Guards for language-level values and host objects.

    isPrimitive("value"); // true (any non-object value)
    isIdentifier("myVar"); // true (valid ECMAScript identifier)
    isSymbol(Symbol("key")); // true
    isFunction(() => {}); // true
    isError(new Error()); // true
    isRegExp(/pattern/); // true
    isDate(new Date()); // true
    isPromise(Promise.resolve()); // true (native promises only)
    isPromiseLike({ then: () => {} }); // true (any thenable, whatever its provenance)
    isIterable([1, 2, 3]); // true
    isAsyncIterable(asyncGenerator()); // true

    Complete coverage of the JSON data model: the recursive Value type, its Scalar leaves, and structural guards for arrays and objects. isArray and isObject validate shape in depth through element predicates or tuple/template descriptors; object templates are closed by default, with the key wildcard turning them open.

    isNull(null); // true
    isBoolean(true); // true
    isNumber(42); // true
    isString("hello"); // true
    isScalar(42); // true (boolean, number, or string)
    isValue({ a: [1, 2], b: "test" }); // true (recursive JSON value)

    isArray([1, 2, 3]); // true
    isArray([1, 2, 3], isNumber); // with element predicate
    isArray(["hello", 42], [isString, isNumber]); // with tuple template
    isArray([], []); // empty array check

    isObject({ a: 1 }); // true
    isObject({ a: 1 }, isNumber); // with entry predicate
    isObject({ a: 1 }, { a: isNumber }); // with closed template
    isObject({ a: 1 }, { a: isNumber, [key]: isAny }); // with open template
    isObject({ a: 1 }, { a: isNumber, b: v => isOptional(v, isString) }); // with optional field
    isObject({ value: 42 }, { value: v => isUnion(v, [isString, isNumber]) }); // with union field
    isObject({}, {}); // empty object check

    Higher-order guards that combine simpler ones into arbitrary type expressions: isUnion for A | B and isIntersection for A & B. isAny acts as a wildcard that always succeeds, typically used as a placeholder inside templates.

    isAny("test"); // true (wildcard, always succeeds)
    isUnion("test", [isString, isNumber]); // true (matches isString)
    isUnion(42, [isString, isNumber]); // true (matches isNumber)
    isIntersection({ a: 1 }, [isObject, v => isObject(v, { a: isNumber })]); // true (satisfies all)

    isLazy admits values supplied either eagerly or as no-arg factories; isEager is its dual, rejecting factories and accepting only plain values. Paired with the Lazy / Eager type operators. lazy defers a reference behind a memoising accessor that computes it at most once on first use; eager is its converse, resolving a reference to its value on every call.

    isLazy(() => 42, isNumber); // true (no-arg function)
    isLazy(42, isNumber); // true (plain value)
    isEager(42, isNumber); // true (plain value)
    isEager(() => 42, isNumber); // false (no-arg function rejected)

    lazy(() => 42)(); // 42 (computed once, then memoised)
    eager(() => 42); // 42 (resolved on every call)

    assert validates a value against a type guard or an arbitrary predicate, returning it unchanged on success and throwing a TypeError otherwise, with a message derived from the predicate name or computed from the offending value; guards narrow the result to the guarded type, while plain predicates leave it at its declared type.

    error throws where a statement isn't allowed, turning a failure into an expression: Error causes are thrown as they are, anything else wrapped in a generic Error reporting its string representation.

    assert(input, isString); // returns input as a string, or throws TypeError("expected <string> value")
    assert(data, isNumber, "count must be numeric"); // with a fixed message
    assert(port, port => port > 0, port => `expected positive port <${port}>`); // with a computed message

    const port = ports.get(name) ?? error("missing required port");
    const result = await task().catch(reason => error(reason)); // rethrow a reason of unknown type

    Bind a value to a mapper of its own, so a computation reads as a scoped expression rather than as a temporary variable followed by a statement, with the bound name free to shadow the one the value was computed from. map always calls the mapper, whatever the value; opt extends the same mapper with a tolerance for a missing value, short-circuiting to undefined without calling it, or to a fallback of its own, supplied either outright or deferred until the value actually turns out to be missing. Definedness is about assignment rather than emptiness, so null is mapped like any other value.

    map(8080, port => `localhost:${port}`); // "localhost:8080"

    opt(ports.get(name), port => `localhost:${port}`); // string or undefined (the mapper is not called)
    opt(ports.get(name), port => `localhost:${port}`, "localhost:80"); // string
    opt(ports.get(name), port => `localhost:${port}`, () => probe()); // string (probed only if the port is missing)

    Variables

    IdentifierPattern

    Regular expression matching ECMAScript Identifier names.

    key

    Wildcard symbol for open template validation in isObject.

    Type Aliases

    Nullable

    Nullable value.

    Optional

    Optional value.

    Defined

    Defined value.

    Primitive

    ECMAScript primitive value.

    Identifier

    ECMAScript Identifier.

    Value

    Immutable JSON value.

    Scalar

    Immutable JSON scalar.

    Array

    Immutable JSON array.

    Object

    Immutable JSON object.

    Guard

    A type guard function.

    Union

    Extracts the union of guarded types from an array of type guards.

    Intersection

    Extracts the intersection of guarded types from an array of type guards.

    Lazy

    A value or a function returning a value.

    Eager

    The eager counterpart of a Lazy reference.

    Functions

    isNullable

    Checks if a value is Nullable.

    isOptional

    Checks if a value is Optional.

    isDefined

    Checks if a value is Defined.

    isPrimitive

    Checks if a value is a Primitive.

    isIdentifier

    Checks if a value is a valid Identifier.

    isSymbol

    Checks if a value is a symbol.

    isFunction

    Checks if a value is a function.

    isError

    Checks if a value is an Error instance.

    isRegExp

    Checks if a value is a RegExp instance.

    isDate

    Checks if a value is a Date instance.

    isPromise

    Checks if a value is a promise.

    isPromiseLike

    Checks if a value is thenable.

    isIterable

    Checks if a value is iterable.

    isAsyncIterable

    Checks if a value is async iterable.

    isValue

    Checks if a value is a valid JSON value.

    isNull

    Checks if a value is null.

    isScalar

    Checks if a value is a JSON scalar.

    isBoolean

    Checks if a value is a boolean.

    isNumber

    Checks if a value is a finite number.

    isString

    Checks if a value is a string.

    isArray

    Checks if a value is an array.

    isObject

    Checks if a value is a plain object.

    isAny

    Wildcard type guard that always succeeds.

    isUnion

    Checks if a value satisfies any of the provided type guards.

    isIntersection

    Checks if a value satisfies all the provided type guards.

    isLazy

    Checks if a value is a Lazy reference.

    isEager

    Checks if a value is an Eager reference.

    lazy

    Defers a value to first use.

    eager

    Resolves a Lazy reference to its value.

    assert

    Validates a value against a type guard or a predicate.

    error

    Throws an error in expression contexts.

    map

    Applies a mapper to a value.

    opt

    Applies a mapper to an optional value, short-circuiting an undefined one.