vator
![License](https://img.shields.io/github/license/andr-ii/vator?color=blue&label=%C2%A9%20license)
Assert validator for TypeScript projects.
Installation
npm install vator
Usage
import { v, validate, buildSchema } from 'vator';
const { v, validate, buildSchema } = require('vator');
Examples
Primitives
Will validate that value
is a string type:
const value = 'some';
validate(value, v.string);
Will throw an error if value is not matching the type:
const value = 22;
validate(value, v.string);
Error:
Validation failed: value has type 'number', but 'string' type is required.
Objects and Arrays
Will validate that value
is an object with described fields.
Also it's more convenient to use buildSchema
helper to get schema
and ResultType
.
Note
ReturnType
is an empty object, only refers to valid result type!.
const value: unknown = {
name: 'some-name',
age: 100,
isOnline: false,
updatedAt: '2023-05-22T14:32:34.324Z',
unknownData: [2, 'foo', false]
cars: [
{
model: 'bmw',
year: 2017
},
{
model: 'audi',
year: null
}
]
};
const { schema, ResultType } = buildSchema({
name: v.string,
age: v.optional.number,
isOnline: v.maybe.boolean,
updatedAt: v.Date,
unknownData: v.unknown,
cars: v.array(v.object({
model: v.literal('bmw', 'audi'),
year: v.nullable.number
}))
});
validate(value, schema)
Also value
will then have valid types (because validate()
asserts them)
![Alt text](ssh://git@github.com/andr-ll/vator/raw/HEAD/./assets/vator-example.png)