awesome-type-check
A JavaScript library that provides runtime type checks / schema validation for JavaScript data.
This library generates types that are on JSON schema format and this makes the types easy to parse and generate documentation from. You can use a JSON schema validator like ajv (and ajv-keywords) to validate the types if you like but this library has validation logic built in (with a subset of the JSON schema rules).
This library provides:
- A thin layer of syntactic sugar on top of JSON schema
- Extensions to JSON schema - essentially the addition of a
validate
function - that allows us to do typeof/instanceof checks as well as any custom validation that we need for our types. JSON schema is great for validating JSON data but JSON data only has six different types (object, array, string, number, boolean, and null). In JavaScript we typically need to validate more types and this library aims to help with that.
Use Cases for this Library
- Form and model validation
- Type checking options objects and other function arguments
- Validating types of properties passed to React components
- Ability to generate API documentation from types. Types are just JSON schema data structures with validate functions
Installation
npm install awesome-type-check
Usage
const typeErrors TypeError ObjectType StringType Enum Required = const Username = const User = const user = name: 'Joe' tags: 'admin' 'vip' username: 'j' status: 'foobar' const errors = errorslength // => 2errors // => trueerrors0message // => 'must have at least 3 characters but had only 1'errors0path // => ['username']errors1message // => 'must be one of: active, inactive'errors1path // => ['status']
What is a Type?
A type can be specified as:
- A string that represents a type returned by the
typeOf
function, i.e.number
,string
,boolean
,function
,object
,array
etc. ThetypeOf
function used by this library is essentially the built-in JavaScripttypeof
with a few extensions such asnull
,undefined
,NaN
,Infinity
,array
,date
,error
, andregexp
. A string type can also have the valueany
which will validate against all values. Within anObjectType
you can add an exclamation mark to the type of a value to indicate that the corresponding key is required, i.e.number!
. You can specify multiple types in a string by separating them by pipes, i.e.string|number
. - An array containing a single type, i.e. ['string']. This will validate all values that are arrays where all items are of the given type (syntactic sugar for ArrayType).
- A
validate
function. The validate function can either be a predicate that returnstrue
orfalse
or a function that returnsundefined
or errors. If the validate function returnstrue
orundefined
then the data is considered valid and otherwise it is considered invalid. Errors are typically an array of TypeError objects. - A JSON schema object that optionally contains a
validate
function
Built-In Types
- StringType
- NumberType
- BoolType
- NullType
- Enum
- InstanceOf
- TypeOf
- ObjecType
- ExactObject
- ObjectOf
- NestedObject
- ArrayType
- AllOf
- AnyOf
In addition to the types listed above you can create your own types by using custom validate functions.
Options
All built-in types take an options argument and the following options are shared across all types:
title
- the name of the type, for documentation purposesdescription
- a description of the type, for documentation purposesisRequired
- used to indicate that the corresponding key in an object is required (equivalent to (Required)[#required])
Validating Function Arguments
const assertType assertOptions Enum = { if optionstype === 'square' return length * length else return MathPI * Math } Math // => 20 // => 25Math // => 20 // => throws /must be one of: square, circle/
Basic Types Represented as Strings
Here is an example of a typeOf
type represented as a string:
const typeErrors isValid = const Bonus = 'number' // => undefined // => true0message // => 'must be of type number but was string' // => false
You can allow for multiple types by separating them by a pipe (equivalent to AnyOf):
const typeErrors = const Bonus = 'number|string' // => undefined // => undefined0message // => 'must be of type number|string but was boolean'
String types can be converted to JSON schema objects with typeObject
:
const typeObject = const MyNumber = typeof MyNumber // => 'object'MyNumber // => {type: 'number', title: 'number', description: 'TypeOf(number)', arg: 'number'}typeof MyNumbervalidate // => 'function'
TypeOf
Basic types with additional metadata can be created with the TypeOf
function:
const typeErrors isValid TypeOf = const Bonus = // => undefined // => true0message // => 'must be of type Bonus (number) but was string'Bonus // => {type: 'number', title: 'Bonus', description: 'Amount of bonus points for a user', arg: 'number'}
You can also provide TypeOf
with an array of types (equivalent to AnyOf(types)
):
const typeErrors TypeOf = const Bonus = // => undefined // => undefined0message // => 'must be of type number|boolean but was string'
Custom Validate Functions
Here is an example of a predicate validate function:
const typeErrors isValid = const isEven = typeof v === 'number' && v % 2 === 0 // => undefined // => true // => false
Validate functions that are anonymous JavaScript predice functions (that return true/false) are opaque in the sense that they don't
have a name (which can be useful for documentation and errors) and they don't provide a specific/custom error message. If you need to generate
documentation from your types or if you are targeting end users you probably want your validate functions to be named
JavaScript functions (or be created with Validate
, se below) and you want them to return a useful error message.
Here is the same type as above implemented as a validate function that returns undefined
or errors:
const typeErrors isValid TypeError = const isEven = { if typeof v === 'number' && v % 2 === 0 return undefined else return isEven v 'must be an even number' } // => undefined0message // => 'must be an even number' // => true // => false
Here is an example of using the Validate
function to create the same type:
const typeErrors isValid TypeError Validate = const isEven = { if typeof v === 'number' && v % 2 === 0 return undefined else return isEven v 'must be an even number' }const IsEven = // => undefined0message // => 'must be an even number' // => true // => false
Validating Nested Data
You can use ObjectType
and ArrayType
to validate nested data:
const typeErrors ObjectType ArrayType = const User = // => undefinedconst errors = errorslength // => 3errors0path // => ['username']errors0message // => 'must be of type string but was number'errors1path // => ['items', 0]errors1message // => 'is missing the following required keys: createdAt'errors2path // => ['items', 1, 'name']errors2message // => 'must be of type string but was number'
See NestedObject below for a slightly nicer syntax for nested data.
NestedObject
NestedObject
is a wrapper around ObjectType
that provides some syntactic sugar for validating nested data.
Any object literals nested in the structure provided to NestedObject
will be wrapped by the ObjectType
function (i.e. interpreted as object properties) unless they contain a validate
property with a value
of type function (i.e. any nested built-in types will be preserved):
const typeErrors NestedObject = const User = // => undefinedconst errors = errorslength // => 3errors0path // => ['username']errors0message // => 'must be of type string but was number'errors1path // => ['items', 0]errors1message // => 'is missing the following required keys: createdAt'errors2path // => ['items', 1, 'name']errors2message // => 'must be of type string but was number'
TypeError
On validation failure the typeErrors
method will return an array of TypeError
objects with these properties:
stack
- a stacktrace to help you figure out where in your code validation failedmessage
- an error messagetype
- the type definition (JSON schema object) for which validation failedvalue
- the data for which validation failedpath
- if validation failed inside an object or array (or a nested combination of them) the path will show you exactly where in the data structure validation failedcode
- an error category/classification, i.e.maxLength
if a string is too long, ortypeof
if the data type was wrong etc.
StringType
Use StringType
to validate string values and optionally provide minLength
, maxLength
, and pattern
options:
const typeErrors StringType = const Username = // => undefined0message // => 'must be of type StringType but was number'0message // => 'must have at least 3 characters but had only 2' // => ['must have at least 3 characters but had only 1', 'must match pattern ^[a-z0-9_-]+$']Username // => { type: 'string', title: 'StringType', minLength: 3, maxLength: 50, pattern: '^[a-z0-9_-]+$', description: 'String with minimum length 3 and maximum length 50 and pattern ^[a-z0-9_-]+$',}
NumberType
Validates number values with optional minimum
and maximum
restrictions:
const typeErrors NumberType = const Score = // => undefined // => undefined // => undefined0message // => 'must be of type NumberType but was string'0message // => 'must be at least 0 was only -1'0message // 'must be no more than 100 but was 101'Score // => {type: 'number', title: 'NumberType', minimum: 0, maximum: 100, description: 'Number with minimum length 0 and maximum length 100'}
BoolType
Validate that a value is true
or false
, equivalent to TypeOf('boolean'
:
const typeErrors BoolType TypeOf = const Active = // => undefined // => undefined0message // => 'must be of type boolean but was object' // => undefined // => undefined0message // => 'must be of type boolean but was object'Active // => {type: 'boolean', title: 'boolean', description: 'TypeOf(boolean)', arg: 'boolean'}
NullType
Validates that a value is null
. Equivalent to TypeOf('null')
:
const typeErrors NullType = // => undefined0message // => 'must be of type null but was undefined'0message // => 'must be of type null but was array'
ObjectType
Use ObjectType
to validate objects, accepts JSON schema equivalent options required
and additionalProperties
:
const typeErrors ObjectType ArrayType Required = const User = // => undefinedconst errors = errorslength // => 2errors0path // => ['username']errors0message // => 'must be of type string but was number'errors1path // => ['score']errors1message // => 'must be of type number but was boolean'
ExactObject
Use ExactObject
to validate objects where no additional properties other than those specified are allowed. Syntactic sugar for ObjectType(properties, {addtionalProperties: false})
:
const typeErrors ExactObject = const User = // => undefinedconst errors = errorslength // => 1errors0message // => 'has the following invalid keys: userName'
ObjectOf
Use ObjectOf
to validate that all values of an object must be of a certain type. Syntactic sugar for ObjectType({}, {patternProperties: {'.*': valueType}})
:
const typeErrors ObjectOf = const Callbacks = // => undefinedconst errors = errorslength // => 1errors0message // => 'must be of type function but was array'
ArrayType
Use ArrayType
to validate that a value must be an array
. Options are minItems
and maxItems
:
const typeErrors ArrayType = const Numbers = // => undefinedconst errors = errorslength // => 2errors0message // => 'must be of type number but was string'errors1message // => 'must have at least 2 items but had only 1'
There is also syntactic sugar available that allows you to use an array literal to represent an ArrayType
:
const typeErrors = const Numbers = 'number' // => undefined0message // => 'must be of type number but was string'
Enum
Use Enum
to check that a value is in a given set of values:
const typeErrors Enum = const Status = // => undefined // => undefined0message // => 'must be one of: active, inactive'
InstanceOf
Use InstanceOf
to check that a value has a certain constructor (or class):
const typeErrors InstanceOf = { thismake = make thismodel = model} // => undefined // => undefined0message // => 'must be instanceof RegExp'
Required
You can use Required
to mark a key in an ObjectType
as required:
const typeErrors ObjectType Required = const User = // => undefined0message // => 'is missing the following required keys: username'
You can also mark keys with types represented as strings as required by adding an exclamation mark:
const typeErrors ObjectType = const User = // => undefined0message // => 'is missing the following required keys: username'
AllOf
Use AllOf
to check that a value must validate against all of the given types (intersection type):
const typeErrors NumberType AllOf = const PositiveNumber = const DivisibleByTen = v % 10 === 0 ? undefined : 'must be divisible by 10'const Score = // => undefined // => undefined0message // => 'must be divisible by 10'0message // => 'must be of type NumberType but was string'
AnyOf
Use AnyOf
to check that a value must validate against at least one of the given types (union type):
const typeErrors NumberType AnyOf = const PositiveNumber = const DivisibleByTen = v % 10 === 0 ? undefined : 'must be divisible by 10'const Score = // => undefined // => undefined // => undefined0message // => 'must be of type AnyOf(NumberType, DivisibleByTen)'0message // => 'must be of type AnyOf(NumberType, DivisibleByTen)'
TODO
- ESLint
- Unit test for NestedObject
- Add error toJSON test (i.e. check JSON.parse(JSON.stringify(error)))
- Always preserve constructor type name (ObjectType, ArrayType etc.) in constructor property?
- Add ajv schema validation to nested type test
- Add comparison to other libraries in RAEDME (prop-types, superstruct, joi etc.)
- Improve generic message if you can extract title
- Create single ES5/UMD file with Babel/Rollup for client side use? Try https://www.pikapkg.com/blog/introducing-pika-pack
- Remove @pika/pack from package.json and from pkg if we can't get it to work properly
- Create a JSFiddle with unpkg (https://medium.com/cameron-nokes/the-30-second-guide-to-publishing-a-typescript-package-to-npm-89d93ff7bccd)
- Test ability to easily generate documentation etc. based on a nested complex type (good navigability and meta data)
- More test cases: Enum, nested objects/arrays, AnyOf, AllOf, custom types, optional arrays (ArrayOrScalar)
- Integration with React when used as PropTypes. Ability to turn off in production. PropTypes compatibility layer?
- Apply to the assertValidOptions use case, maybe in versioned-api?
- Tuple type
Resources
- superstruct - Data Validation. It seems superstruct only reports on the first key having an error, not all keys. This may be an issue for form validation.
- joi - Object Schema Validation
- facebook/prop-types - Type Checking React Props
- type_spec - Runtime Type Checks in Python
- Understanding JSON Schema
- kind-of - Check Type of Value in JavaScript
- Clojure Spec
- Active Record Validations