sindresorhus / ow
- воскресенье, 29 апреля 2018 г. в 00:18:49
TypeScript
Argument type validation
Argument type validation
$ npm install ow
import ow from 'ow';
const unicorn = input => {
ow(input, ow.string.minLength(5));
// …
};
unicorn(3);
//=> ArgumentError: Expected argument to be of type `string` but received type `number`
unicorn('yo');
//=> ArgumentError: Expected string to have a minimum length of `5`, got `yo`Test if value matches the provided predicate.
Create a reusable validator.
const checkPassword = ow.create(ow.string.minLength(6));
checkPassword('foo');
//=> ArgumentError: Expected string to have a minimum length of `6`, got `foo`Returns a predicate that verifies if the value matches at least one of the given predicates.
ow('foo', ow.any(ow.string.maxLength(3), ow.number));All the below types return a predicate. Every predicate has some extra operators that you can use to test the value even more fine-grained.
int8Arrayuint8Arrayuint8ClampedArrayint16Arrayuint16Arrayint32Arrayuint32Arrayfloat32Arrayfloat64ArrayThe following predicates are available on every type.
Inverts the following predicates.
ow(1, ow.number.not.infinite);
ow('', ow.string.not.empty);
//=> ArgumentError: [NOT] Expected string to be empty, got ``Use a custom validation function. Return true if the value matches the validation, return false if it doesn't.
ow(1, ow.number.is(x => x < 10));
ow(1, ow.number.is(x => x > 10));
//=> ArgumentError: Expected `1` to pass custom validation functionInstead of returning false, you can also return a custom error message which results in a failure.
const greaterThan = (max: number, x: number) => {
return x > max || `Expected \`${x}\` to be greater than \`${max}\``;
};
ow(5, ow.number.is(x => greaterThan(10, x)));
//=> ArgumentError: Expected `5` to be greater than `10`MIT