UNPKG

tiny-types

Version:

A tiny library that brings Tiny Types to JavaScript and TypeScript

43 lines 1.44 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.property = property; const and_1 = require("./and"); const Predicate_1 = require("./Predicate"); /** * @desc Ensures that the `property` of the `value` meets the `predicates` * * @example * import { ensure, isGreaterThan, property, TinyType } from 'tiny-types'; * * class Name extends TinyType { * constructor(public readonly value: string) { * super(); * ensure('Name', value, property('length', isGreaterThan(3))); * } * } * * @returns {Predicate<T>} */ function property(propertyName, ...predicates) { return new HaveProperty(propertyName, (0, and_1.and)(...predicates)); } /** @access private */ class HaveProperty extends Predicate_1.Predicate { propertyName; predicate; constructor(propertyName, predicate) { super(); this.propertyName = propertyName; this.predicate = predicate; } /** @override */ check(value) { const result = this.predicate.check(value[this.propertyName]); return result instanceof Predicate_1.Failure ? new Predicate_1.Failure(value, `have a property "${String(this.propertyName)}" that ${result.description}` .replaceAll(/\bbe\b/gi, 'is') .replaceAll(/\beither is\b/gi, 'is either')) : new Predicate_1.Success(value); } } //# sourceMappingURL=property.js.map