Package Exports
- typanion
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (typanion) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Typanion
Static and runtime type assertion library with no dependencies
Installation
yarn add typanionWhy
- 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).
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 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>;
// Then just use your alias:
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),
});API
Type predicates
isArray(values)will ensure that the values are arrays whose values all match the specified schema.isBoolean()will ensure that the values are all booleans. Note that to specifically check for eithertrueorfalse, you can look forisLiteral.isDict(values, {keys?})will ensure that the values are all a standard JavaScript objects containing an arbitrary number of fields whose values all match the given schema. Thekeysoption can be used to apply a schema on the keys as well (this will always have to be strings, so you'll likely want to useapplyCascade(isString(), [...])to define the pattern).isLiteral(value)will ensure that the values are strictly equal to the specified expected value. It's an handy tool that you can combine withoneOfandobjectto parse structures similar to Redux actions, etc. Note that you'll need to annotate your value withas constin order to let TypeScript know that the exact value matters (otherwise it'll cast it tostringinstead).isNumber()will ensure that the values are all numbers.isObject(props, {extra?})will ensure that the values are plain old objects whose properties match the given shape. Extraneous properties will be aggregated and validated against the optionalextraschema.isString()will ensure that the values are all regular strings.isUnknown()will accept whatever is the input without validating it, but without refining the type inference either. Note that by defaultisUnknownwill forbidundefinedandnull, but this can be switched off by explicitly allowing them viaisOptionalandisNullable.isInstanceOf(constructor)will ensure that the values are instances of a given constructor.
Helper predicates
applyCascade(spec, [specA, specB, ...])will ensure that the values all matchspecand, if they do, run the followup validations as well. Since those followups will not contribute to the inference (only the lead schema will), you'll typically want to put here anything that's a logical validation, rather than a typed one (cf the Cascading Predicates section).isOneOf([specA, specB])will ensure that the values all match any of the provided schema. As a result, the inferred type is the union of all candidates. The predicate supports an option,exclusive, which ensures that only one variant matches.isOptional(spec)will addundefinedas an allowed value for the given specification.isNullable(spec)will addnullas an allowed value for the given specification.
Cascading predicates
Cascading predicate don't contribute to refining the value type, but are handful to assert that the value itself follows a particular pattern. You would compose them using applyCascade (cf the Examples section).
hasExactLengthwill ensure that the values all have alengthproperty exactly equal to the specified value.hasMaxLengthwill ensure that the values all have alengthproperty at most equal to the specified value.hasMinLengthwill ensure that the values all have alengthproperty at least equal to the specified value.hasUniqueItemswill ensure that the values only have unique items (mapwill transform before comparing).isAtLeastwill ensure that the values compare positively with the specified value.isAtMostwill ensure that the values compare positively with the specified value.isBase64will ensure that the values are valid base 64 data.isHexColorwill ensure that the values are hexadecimal colors (alphawill allow an additional channel).isInExclusiveRangewill ensure that the values compare positively with the specified value.isInInclusiveRangewill ensure that the values compare positively with the specified value.isIntegerwill ensure that the values are round safe integers (unsafewill allow unsafe ones).isJSONwill ensure that the values are valid JSON, and optionally match them against a nested schema.isLowerCasewill ensure that the values only contain lowercase characters.isNegativewill ensure that the values are at most 0.isPositivewill ensure that the values are at least 0.isISO8601will ensure that the values are dates following the ISO 8601 standard.isUpperCasewill ensure that the values only contain uppercase characters.isUUID4will ensure that the values are valid UUID 4 strings.matchesRegExpwill ensure that the values all match the given regular expression.
Examples
Validate that an unknown value is a port protocol:
const isPort = t.applyCascade(t.isNumber(), [
t.isInteger(),
t.isInInclusiveRange(1, 65535),
]);
isPort(42000);Validate that a value contains a specific few fields, regardless of the others:
const isDiv = t.isObject({
tagName: t.literal(`DIV` as const),
}, {
extra: t.isUnknown(),
});
isDiv({tagName: `div`, appendChild: () => {}});Validate that a specific field is a specific value, and that others are all numbers:
const isModel = t.isObject({
uid: t.String(),
}, {
extra: t.isDict(t.isNumber()),
});
isModel({uid: `foo`, valA: 12, valB: 24});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.