0.4.0 • Published 2 years ago

@meltwater/coerce v0.4.0

Weekly downloads
3,306
License
MIT
Repository
github
Last release
2 years ago

@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\ 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\ Array of instances of provided Type

0.4.0

2 years ago

0.3.1

3 years ago

0.3.0

4 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.0.2

5 years ago

0.0.1

6 years ago