@meltwater/coerce
v0.4.1
Published
A simple javascript package for type checking an object
Downloads
4,700
Readme
@meltwater/coerce
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 coerceType
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 coerceType
any The type each object should bemessage
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