Nobody Packages More

    @meltwater/coerce
    TypeScript icon, indicating that this package has built-in type declarations

    0.4.0 • Public • Published

    @meltwater/coerce

    Build Status A simple javascript package for type checking an object

    Install

    npm i --save @meltwater/coerce

    Usage

    class ValidatedObject {
        constructor({ value }) {
            if(typeof value !== string) {
                throw new TypeError(`options.value must be a string. Provided value: ${value}`);
            }
    
            this.value = value;
            Object.freeze(this);
        }
    }
    
    const badValue = { value: 1234 };
    coerce(badValue, ValidatedObject, 'Booooooom!');
    // This will throw a TypeError with the message 'Booooooom!'
    
    const goodValue = { value: 'so good' };
    const typedValue = coerce(goodValue, ValidatedObject, 'Booooooom');
    // This will return a new object that is an instanceof ValidatedObject with typedValue.value === 'so good'

    API reference

    Table of Contents

    coerce

    If value is an instance of Type, this function returns it. Otherwise this function attempts to construct a new instance Type using value as a constructor parameter.

    Parameters

    • value any The value to coerce
    • Type any The type to return the object as.
    • message string The error message if coercion fails
    • Throws TypeError If the value is not coercable.

    Returns any Instance of provided Type

    coerceArray

    Apply coerce to an array for a single type.

    Parameters

    • values Array<any> The array of values to coerce
    • Type any The type each object should be
    • message string The error message if coercion fails
    • Throws TypeError If values is not an array
    • Throws TypeError One of the array values is not coercable.

    Returns Array<any> Array of instances of provided Type

    Install

    npm i @meltwater/coerce

    DownloadsWeekly Downloads

    6,685

    Version

    0.4.0

    License

    MIT

    Unpacked Size

    18.3 kB

    Total Files

    12

    Last publish

    Collaborators

    • meltwater-legion