Ergonomic, extensible and lightweight validators.
npm install reviewedErgonomic, extensible and lightweight validators.
!Review
!Version
!Downloads
!Size
!Quality
!Coverage
I want to validate unknowns and for the compiler to know the parsed type:
``ts
import { isNumber } from "reviewed";
const parse = (input: unknown) => {
const { valid, parsed } = isNumber(input);
if (valid) {
// Parsed type: number
console.log(parsed);
}
};
`
I want to validate an object and get failure messages for each field:
`ts
import { errors, isNaturalNumberString } from "reviewed";
const paginate = (url: URL): void => {
const isPagination = validateWith({
page: isNaturalNumberString,
size: isNaturalNumberString,
});
const { valid, parsed, error } = isPagination({
page: url.searchParams.get("page"),
size: url.searchParams.get("size"),
});
if (valid) {
console.log(parsed);
} else {
console.error(error);
}
};
`
`ts`
paginate(new URL("https://example.com?page=1&size=10"));
`json`
{
"page": 1,
"size": 10
}
`ts`
paginate(new URL("https://example.com?page=-1"));
`json`
{
"page": "Not a natural number string: '-1'",
"size": "Not a string: null"
}
I want a record with the input and failure messages, not some ridiculous opaque object with error methods!
`ts`
isRecordOf({ a: isNumber, b: isString })({ a: 1, b: 2 });
`json`
{
"valid": false,
"input": { "a": 1, "b": 2 },
"parsed": null,
"error": { "b": "Not a string: 2" }
}
`bash`
npm install reviewed
Documentation and more detailed examples are hosted on Github Pages.
A validation library for TypeScript needs to be:
- Ergonomic
- Validated types can be inferred by the compiler
- Validators can parse the inputs
- Errors are easy to collect
- Extensible
- It is quick to write validators
- It is simple to test validators
- Common validators are available
- Lightweight
- Tiny bundle size
- Fully tree shakeable
reviewed exposes a flexible interface that achieves these goals.
`ts`
isIntegerString("1");
`json`
{
"valid": true,
"input": "1",
"parsed": 1,
"error": null
}
`ts`
isIntegerString("0.5");
`json`
{
"valid": false,
"input": "0.5",
"parsed": null,
"error": "Not an integer 0.5"
}
Webpack warns when a bundle exceeds 250kb, validation is not an optional feature of an application. If the minified size of a package compromises this budget it simply won't be used.
| Package | Version | Minified (kB) |
| ----------- | ------- | ------------- |
| joi | 17.12.0 | 145.5 |
| ajv | 8.12.0 | 119.6 |
| validator | 13.11.0 | 114.2 |
| zod | 3.22.4 | 57.0 |
| yup | 1.3.3 | 40.8 |
| superstruct | 1.0.3 | 11.5 |
Superstruct has good TypeScript support and serves as an inspiration for this package. However, the validation style for this package is designed to be much simpler and more flexible than superstruct with less need for factory functions and simpler failure message customisation.
numbers.ts
`ts
import { Validator, isInteger, validateIf } from "reviewed";
export const isNaturalNumber: Validator
const integer = isInteger(input);
if (!integer.valid) {
return integer;
}
return validateIf(integer.parsed > 0, input, input, "Not a natural number");
};
`
Custom Jest matchers are exposed for testing validators:
jest.config.json
`json`
{
"setupFilesAfterEnv": ["reviewed/dist/testing/jest.js"]
}
tsconfig.json
`json`
{
"files": ["node_modules/reviewed/dist/testing/jest.d.ts"]
}
`ts
import { isNaturalNumberString } from "./strings";
describe("isNaturalNumberString", () => {
it("parses natural number strings", () => {
expect(isNaturalNumberString).toValidate("1");
expect(isNaturalNumberString).toInvalidate({});
expect(isNaturalNumberString).toValidateAs("1", 1);
expect(isNaturalNumberString).toInvalidateWith({}, "Not a string");
});
});
`
For convenience you can define whole suites at once:
`ts
import { isNaturalNumberString } from "./strings";
import { suite } from "reviewed";
suite(isNaturalNumberString, [{ input: "1", parsed: 1 }], {
"Not a string": [undefined, null, true, 1, [], {}],
"Not a number string": ["", "true", "a", "NaN", "Infinity"],
"Not an integer string": ["0.5"],
"Not a natural number string": ["0", "-1"],
});
`
Validators can be chained to validate a payload:
`json`
[{ "name": "a" }, { "name": "b" }]
`ts`
export const isArrayOfNames = isArrayOf(isRecordOf({ name: isString }));
Guards can inform the compiler that the input satisfies a type predicate. This is thanks to TypeScript's is operator:
`ts`
(input: unknown): input is string => {};
Validators make assertions about the parsed type:
`ts
import { isNumber } from "reviewed";
const { valid, parsed } = isNumber(x);
if (valid) {
// Parsed type: number
console.log(parsed + 1);
}
`
We can convert this to a guard and apply the assertion to the input instead:
`ts
import { guard, isNumber } from "reviewed";
if (guard(isNumber)(input)) {
// Parsed type: number
console.log(input + 1);
}
`
Validators can be made optional:
`ts
interface Person {
name?: string;
}
const isPerson = isRecordOf
`
`ts`
isPerson({});
`json`
{
"valid": true,
"parsed": { "name": "Joel" }
}
`ts`
isPerson({ name: "Joel" });
`json`
{
"valid": true,
"parsed": { "name": "Joel" }
}
Strictly speaking, { name: optional(isString) } implies that the interface is { name: string | undefined } which allows name to be explicitly undefined. Since this is never useful the interface is interpreted as being { name?: string } which is simpler than having a separate function for strictly optional values.
Note that there has been lots of discussion around changing the way TypeScript handles undefined vs optional parameters: https://github.com/Microsoft/TypeScript/issues/12400. Rather than implementing some casts under the hood to fight the type checker this library leaves it up to the developer to be explicit:
`ts`
const isPerson = isRecordOf
Whereas this will throw an error when strict optional checking is enabled:
`ts`
const isPerson: Validator
Array literals can be converted directly to validators:
`ts`
const builds = ["dev", "prod"] as const;
const isBuild = isOneOf(builds);
`ts`
isBuild("dev");
`json`
{
"valid": true,
"parsed": [3, 1]
}
`ts`
isBuild("local");
`json`
{
"valid": false,
"error": "Not one of ['dev', 'prod']: 'local'"
}
Validators take an unknown input and return a record that implements the Valid or Invalid interfaces:
`ts
interface Valid
valid: true;
input: unknown;
parsed: T;
error: null;
}
interface Invalid
valid: false;
input: unknown;
parsed: null;
error: ValidationErrors
}
type Validated
type Validator
`
Inputs can be validated directly:
`ts
const validate:
const invalidate:
const validateWith:
const invalidateWith:
`
Helper factories are provided:
`ts
const validateIf:
const validateRegex:
const validateAll:
const validateEach:
const validateOr:
const validateEachOr:
`
Validators can be used to filter inputs:
`ts`
const filterValid:
Validators can be inverted or joined:
`ts
const not:
const both:
const either:
const optional =
const isArrayOf:
const isRecordOf:
`
Results can be merged:
`ts
const all:
const any:
const merge:
const sieve:
`
Validation errors can be converted to native errors:
`ts`
const fail:
Common validators are provided out of the box:
`ts
const isUndefined: Validator
const isNull: Validator
const isBoolean: Validator
const isNumber: Validator
const isString: Validator
const isObject: Validator
const isInteger: Validator
const isNaturalNumber: Validator
const isBooleanString: Validator
const isNumberString: Validator
const isIntegerString: Validator
const isNaturalNumberString: Validator
const isJSONString: Validator
const isArray: Validator
const isNonEmptyArray: Validator
const isNumberArray: Validator
const isStringArray: Validator
const isRecord: Validator
const isNonEmptyRecord: Validator
const isEmail: RegexValidator<"user" | "domain">;
const isOneOf:
const isManyOf:
`
JavaScript has some famously confusing types:
`ts`
typeof NaN;
`json`
"number"
Care is taken to make primitive types easier to work with.
#### Numbers
`ts`
const isNumber: Validator
validateIf(typeof input === "number" && isFinite(input), input, input, "Not a number");
| Input | Parsed | Error |
| -------- | ------ | ------------- |
| 1 | 1 | null |
| NaN | null | Not an number |
| Infinity | null | Not an number |
| "" | null | Not an number |
#### Objects
`ts`
const isObject: Validator
| Input | Parsed | Error |
| ----- | ------ | ------------- |
| \[] | \[] | null |
| {} | {} | null |
| "" | null | Not an object |
#### Records
`ts`
const isRecord: Validator
validateIf(isObject(input).valid && !isArray(input).valid, input, input, "Not a record");
| Input | Parsed | Error |
| ----- | ------ | ------------- |
| \[] | null | Not a record |
| {} | {} | null |
| "" | null | Not an object |
Hey let's write an isArrayOf and isRecordOf function:
`ts`
const isArrayOf:
const isRecordOf:
const isRecordOfAtLeast:
But wait we already have:
`ts`
const validateAll:
const validateWith:
const validateWithAtLeast:
That's because they're the same thing woah...
So we can just alias them:
`ts`
export const isArrayOf = validateAll;
export const isRecordOf = validateWith;
export const isRecordOfAtLeast = validateWithAtLeast;
To install dependencies:
`bash`
yarn install
To run tests:
`bash`
yarn test
To generate the documentation locally:
`bash`
yarn docs
To run linters:
`bash`
yarn lint
To run formatters:
`bash`
yarn format
Please read this repository's Code of Conduct which outlines our collaboration standards and the Changelog for details on breaking changes that have been made.
This repository adheres to semantic versioning standards. For more information on semantic versioning visit SemVer.
Bump2version is used to version and tag changes. For example:
`bash``
bump2version patch
- Joel Lefkowitz - Initial work
Lots of love to the open source community!


