UNPKG

type-fns

Version:

A set of types, type checks, and type guards for simpler, safer, and easier to read code.

57 lines 2.71 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.withAssure = exports.asAssure = exports.AssureIsOfTypeRejectionError = void 0; const helpful_errors_1 = require("helpful-errors"); class AssureIsOfTypeRejectionError extends helpful_errors_1.HelpfulError { } exports.AssureIsOfTypeRejectionError = AssureIsOfTypeRejectionError; /** * what: a wrapper which takes a boolean type.check and converts it into a type.assure * what^2: * - a type.check uses typescript's type.predicate capacity to narrow a type via boolean (i.e., `input is T`) * - a type.assure uses this type.check and throws an error if the result was false, assuring that if a result is returned, it is of the desired type * why: * - makes it easy to fail fast if expectations are not met * - simplifies code by rejecting code paths that should not happen, allowing focus on only the expected code paths, rather than having 'if/then' statements all over the place * why^2: * - simplicity++ -> readability++ -> speed++ && maintainability++ */ const asAssure = (assess, options) => { const name = options?.name ?? assess.name; // todo: get resource name more reliably const assure = (input) => assess(input) ? input : (() => { throw new AssureIsOfTypeRejectionError(`assure.rejection: input does not satisfy type.check '${name}'`, { check: name, input: input === undefined ? 'undefined' : input, }); })(); return assure; }; exports.asAssure = asAssure; /** * what: a wrapper which takes a type.check and adds an .assure and .assess to it * what^2: * - a type.check uses typescript's type.predicate capacity to narrow a type via boolean (i.e., `input is T`) * - a type.assure uses this type.check and throws an error if the result was false, assuring that if a result is returned, it is of the desired type * - an .assure and .assess can be added to a function, enabling backwards compatible default .assess usage while still exposing explicit .assure and .assess utilities * why: * - makes it easy to extend type.checks w/ .assure in a backwards compatible way * - enables convenient custom utilities to fail fast if expectations are not met * why^2: * - simplicity++ -> readability++ -> speed++ && maintainability++ * * note * - leverages `asAssure` under the hood */ const withAssure = (assess, options) => { const assure = (0, exports.asAssure)(assess, options); const result = function (...input) { return assess(...input); }; result.assess = assess; result.assure = assure; return result; }; exports.withAssure = withAssure; //# sourceMappingURL=withAssure.js.map