What is typanion?
The typanion npm package is a comprehensive solution for runtime input validation in JavaScript and TypeScript applications. It allows developers to ensure that the data their applications process meets certain criteria, thereby preventing unexpected errors and improving data integrity. Typanion offers a flexible and expressive API for defining validation rules, making it suitable for a wide range of use cases.
What are typanion's main functionalities?
Basic Type Validation
This feature allows for basic type validation, such as checking if a value is a number. The code sample demonstrates how to use the `isNumber` function to validate numeric values.
{"const {isNumber} = require('typanion');
const validate = isNumber();
console.log(validate(42)); // {ok: true, errors: []}
console.log(validate('hello')); // {ok: false, errors: [...]}"}
Complex Object Validation
This feature enables complex object validation, allowing developers to validate nested objects and apply multiple validation rules. The code sample shows how to validate a user object with both `name` and `email` fields.
{"const {isObject, isString, applyCascade} = require('typanion');
const validateUser = isObject({
name: isString(),
email: applyCascade(isString(), [isEmail()])
});
console.log(validateUser({name: 'John Doe', email: 'john@example.com'})); // {ok: true, errors: []}"}
Custom Validation Rules
Typanion allows for the creation of custom validation rules. This feature is particularly useful for domain-specific validations. The code sample illustrates how to define and use a custom validator to check if a person is an adult.
{"const {createValidator} = require('typanion');
const isAdult = createValidator({
test: (value) => value >= 18,
message: (value) => `${value} is not an adult`
});
console.log(isAdult(21)); // {ok: true, errors: []}
console.log(isAdult(16)); // {ok: false, errors: [...]}"}
Other packages similar to typanion
joi
Joi is a powerful schema description language and data validator for JavaScript. It offers a similar range of functionalities for validating data structures but with a slightly different API design. Compared to typanion, Joi might be considered more feature-rich but also more complex for simple use cases.
yup
Yup is a lean JavaScript schema builder for value parsing and validation. It integrates well with form libraries and is often used in front-end applications. While it provides similar validation capabilities, Yup focuses more on simplicity and ease of use compared to the more flexible and comprehensive approach of typanion.
validator
Validator is a library of string validators and sanitizers. Unlike typanion, which offers a wide range of validation types and custom validation logic, Validator focuses primarily on string validation, making it more specialized but less versatile for different data types.
Typanion
Static and runtime type assertion library with no dependencies
Installation
yarn add typanion
Why
- Typanion can validate nested arbitrary data structures
- Typanion is type-safe; it uses type predicates
- Typanion allows you to derive types from your schemas
- Typanion can report detailed error reports
Compared to yup, Typanion has a better inference support for TypeScript + supports isOneOf
. Its functional API makes it very easy to tree shake, which is another bonus (although the library isn't very large in itself).
Documentation
Check the website for our documentation: mael.dev/typanion.
Usage
First define a schema using the builtin operators:
import * as t from 'typanion';
const isMovie = t.isObject({
title: t.isString(),
description: t.isString(),
});
Then just call the schema to validate any unknown
value:
const userData = JSON.parse(input);
if (isMovie(userData)) {
console.log(userData.title);
}
Passing a second parameter allows you to retrieve detailed errors:
const userData = JSON.parse(input);
const errors: string[] = [];
if (!isMovie(userData, {errors})) {
console.log(errors);
}
You can also apply coercion over the user input:
const userData = JSON.parse(input);
const coercions: Coercion[] = [];
if (isMovie(userData, {coercions})) {
for (const [p, op] of coercions) op();
}
You can derive the type from the schema and use it in other functions:
import * as t from 'typanion';
const isMovie = t.isObject({
title: t.isString(),
description: t.isString(),
});
type Movie = t.InferType<typeof isMovie>;
const printMovie = (movie: Movie) => {
};
Schemas can be stored in multiple variables if needed:
import * as t from 'typanion';
const isActor = t.isObject({
name: t.isString();
});
const isMovie = t.isObject({
title: t.isString(),
description: t.isString(),
actors: t.isArray(isActor),
});
License (MIT)
Copyright © 2020 Mael Nison
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.