A simple javascript package for type checking an object
npm i --save @meltwater/coerce
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'
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.
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
Apply coerce
to an array for a single type.
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