fully-typed
Run time type validation, transformation, and error generator that works out of the box on primitives, objects, arrays, and nested objects. Also extensible for custom types.
Features
- Create schemas to validate values against.
- Built in support for arrays, booleans, functions, numbers, objects, strings, and symbols.
- Extensible - use plugins or create your own to integrate more types.
- Get detailed error messages when a wrong value is run against a schema.
- Auto throw errors when normalizing or validating.
Example
const Typed = ; const schema = ; // will only add numbers, throws errors otherwiseexports { a = schema; // throw an error if not a number or if undefined defaults to 0 b = schema; return a + b;};
Example
const Typed = ; const schema = ; { const config = schema; // If the input is invalid an error is thrown // with specifics as to why it failed // ... do more stuff}
Example
const Typed = ; // define a schemaconst positiveIntegerSchema = ; // default value usedconst value = positiveIntegerSchema; // value === 100 // check for errors - valid valuespositiveIntegerSchema; // null - no errorpositiveIntegerSchema; // null - no error // check for errors - invalid valuespositiveIntegerSchema; // Invalid number. Must be greater than or equal to 0. Received: -1positiveIntegerSchema; // Invalid number. Must be an integer. Received: 1.2positiveIntegerSchema; // Invalid value. Expected a number. Received: "1" // throw errorspositiveIntegerSchema; // throws errorpositiveIntegerSchema; // validate will run prior to normalization - throws error
Table of Contents
Schema Configurations
Shared Configuration Options
All types defined share the following common configuration options:
-
default - A value to use during normalization if the value is
undefined
. This is especially useful for the properties of object configurations.const schema =;const value1 = schema; // value1 === 'Hello, Bob!'const value2 = schema; // value2 === 'Hello, World!' -
enum - (Array) A non-empty array of acceptable values. Values are compared using triple equals
===
.const schema =;// these do not produce errorsschema;schema;schema;// these do produce errorsschema;schema;schema; -
transform - (Function) This function is only run during normalization. It receives the validated value and must return a value. The value returned will be the result of normalization.
// a schema that normalizes any value to a booleanconst schema =; -
validator - (Function) This function provides an easy method for adding some custom validation to a schema. The validator will be passed the value as its only parameter. Returning a truthy value means the value is valid, returning a string or a falsy value signifies an invalid value. If a string is returned then the value for the string is placed in the error message.
// good luck getting this to validateconst schema =;
Array
An array type will require the input to be an array.
Type Aliases: 'array'
, Array
In addition to the shared configuration options it also has these options:
-
maxItems - (Number) The maximum number of items that the array can contain. Defaults to
undefined
. -
minItems - (Number) The minimum number of items that the array must contain. Defaults to
0
. -
schema - (Object) A configuration schema to apply to each item in the array. For example, you can specify that the array must be an array of numbers.
// schema is for an array of numbersconst schema =; -
uniqueItems - (Boolean) If set to true then each item in the array must be unique. Defaults to
false
.const schema =;schema; // no errorsschema; // error
Boolean
An boolean type will accept any value and transform it into a boolean unless the strict
option is set. Under strict
this type will only accept a boolean.
Type Aliases: 'boolean'
, Boolean
In addition to the shared configuration options it also has this option:
-
strict - (Boolean) Set to true to require that the type be a boolean. Defaults to
false
.const loose =;const strict =;loose; // no errorsstrict; // errorstrict; // no errorsconst value = loose; // value === true
Date
A date type will require that the input be a valid Date or that it be a value that can be converted to a valid Date.
Type Aliases: 'date'
, Date
In addition to the shared configuration options it also has these options:
-
max - (Date, string, number) The maximum allowed date value. Defaults to
undefined
.const schema =;schema; // no errorsschema; // error -
min - (Date, string, number) The minimum allowed date value. Defaults to
undefined
.const schema =;schema; // no errorsschema; // error
Function
An function type will require the input to be a function.
Type Aliases: 'function'
, Function
In addition to the shared configuration options it also has these options:
-
maxArguments - (Number) The maximum number of arguments that the function can define as parameters. Defaults to
undefined
.const schema =;schema; // no errorsschema; // error -
minArguments - (Number) The minimum number of arguments that the function can define as parameters. Defaults to
0
.const schema =;schema; // no errorsschema; // error -
named - (Boolean) Require the function to be named. Defaults to
false
.const schema =;schema; // no errorsschema; // error
Number
An number type will require the input to be a number.
Type Aliases: 'number'
, Number
In addition to the shared configuration options it also has these options:
-
exclusiveMax - (Boolean) Whether the maximum value should be included as allowed or not. Defaults to
false
.const schema =;schema; // no errorsschema; // error -
exclusiveMin - (Boolean) Whether the minimum value should be included as allowed or not. Defaults to
false
.const schema =;schema; // no errorsschema; // error -
integer - (Boolean) Whether the value must be an integer. Defaults to
false
.const schema =;schema; // no errorsschema; // error -
max - (Number) The maximum allow value. Defaults to
undefined
.const schema =;schema; // no errorsschema; // no errorsschema; // error -
min - (Number) The minimum allow value. Defaults to
undefined
.const schema =;schema; // errorschema; // no errorsschema; // no errors
Object
An object type will require the input to be an object. You can also specify which properties are required and the schema expected for individual properties.
Normalization of this type produces a new object.
Type Aliases: 'object'
, Object
In addition to the shared configuration options it also has these options:
-
allowNull - (Boolean) Whether
null
is an acceptable value. Defaults totrue
.const nullSchema =;const notNullSchema =;nullSchema; // no errorsnullSchema; // no errorsnotNullSchema; // no errorsnotNullSchema; // error -
clean - (Boolean) During normalization remove any properties that are not defined in the schema's properties. Defaults to
false
.const schema =;const value = schema; -
properties - (Object) Define the properties that can be part of this object. Each property takes a full schema configuration. Each property is also given a
required
property that can be set to true.const schema =;schema; // no errorsschema; // error -
schema - (Object) A configuration schema to apply to each property on the object. This is useful for allowing objects to have any property but requiring that each property adhere to a schema. If specific properties are defined then the schema defined here will be extended by and superseded by the specific property's schema.
const schema =;schema; // no errorsschema; // errorThe following example shows a one-of general schema definition. All variations of the general schema are possible extensions across the property specific schemas.
const schema =;schema; // no errorsschema; // error
One-Of
It is possible to allow multiple variations of schemas. For example, you may want to allow numbers and strings.
const schema = ; schema; // no errorsschema; // no errorsschema; // errorschema; // error
String
A string type will require the input to be a string.
Type Aliases: 'string'
, String
In addition to the shared configuration options it also has these options:
-
maxLength - (Number) The maximum length to allow for the string. Defaults to
undefined
.const schema =;schema; // no errorsschema; // error -
minLength - (Number) The minimum length to allow for the string. Defaults to
0
.const schema =;schema; // no errorsschema; // error -
pattern - (RegExp) A regular expression object to test against the string. Defaults to
undefined
.const schema =;schema; // no errorsschema; // error
Symbol
A symbol type will require the input to be a symbol.
Type Aliases: 'symbol'
, Symbol
This type inherits the shared configuration options and has no options of its own.
Schema Instance
A schema is generated by passing a schema configuration into the Typed function:
const Typed = ; // define a schemaconst schema =
Once a schema is created you can check a value for errors, normalize a value, or validate a value.
config
Get a copy of the configuration that was used to define the schema for the current instance.
const schema = const config = schemaconfig; // => { type: Object, allowNull: false }
error
Test a value for errors. If the value does produce an error then a string is returned that details the cause of the error.
Parameters
-
value - The value to do error checking on.
-
prefix - An optional string to append to the beginning of an error message. Defaults to an empty string:
''
.
Returns null
if no errors otherwise a string with error details.
const schema = ; schema; // nullschema; // "Expected a number"
normalize
Validate a value and if an error is not thrown then begin normalization. Normalization differs for different types, but the essential role is to get the value into a state where you are ready to work with it. For example, booleans are normalized to true
or false
from truthy or falsy values respectively.
Parameters
- value - The value to normalize.
Returns The new value.
const schema = ; const value1 = schema; // value1 === trueconst value2 = schema; // value2 === false
validate
The validate function checks for errors and if there is one it throws an error.
Parameters
-
value - The value to run validation on.
-
prefix - An optional string to append to the beginning of an error message. Defaults to an empty string:
''
.
Returns undefined.
const schema = ; schema; // no error thrownschema; // throws an error
Plugins
The fully typed library can be extended with new types.
Use an Existing Plugin
-
Require the plugin in your project along with
fully-typed
. -
Register the plugin with
fully-typed
.const FullyTyped = ;const plugin = ;FullyTypedcontrollers; -
Now you can create schema's that use that plugin's type and associated configurations.
Write a Plugin
A plugin is created by defining a typed controller. See the example.
-
Define a constructor function that accepts a configuration as it's only parameter.
{ } -
Define and validate the configuration properties that are important to your controller.
-
Define the controller's properties. These are often similar or derived from the configuration properties.
-
Optionally define the error generator function on the prototype of the controller. This function will be used for normalization and validation.
MyControllerprototype { }This function will receive two parameters when called: 1) the value to validate, 2) a prefix to add to the beginning of any returned error messages.
This function should return a string with an error message if an invalid value is passed in, otherwise it should return
null
. -
Optionally define the normalize function. This function will be called after passing validation and can make any transformations to the value.
MyControllerprototype { }This function receives the value parameter. It must return the normalized value.
-
Provide the registration directive. This tells
full-typed
what aliases to assign to your controller and what dependencies this controller has. All controllers will automatically inherit from the Typed core controller.MyControllerregister =aliases: 'my-controller'dependencies:The alias can be any value (primitive or object) but each alias must be unique within the entire system of typed controllers. The dependencies can reference the typed controllers by any alias they are registered with.
-
Register your controller.
TypedDate Controller Example
This is one of the built in controllers, but here it is documented to help you create your own controllers / plugins.
moduleexports = TypedDate; // #1 - Define the controller constructor { const max = ; const min = ; // #2 - define and validate configuration properties if config && !max throw Error'Property max could not be converted to a valid date. Received: ' + configmax; if config && !min throw Error'Property min could not be converted to a valid date. Received: ' + configmin; if max !== undefined && min !== undefined && min > max throw Error'The max date value must be greater than or equal to the min date value.'; // #3 - define the controller's properties Object;} // #4 - Define the error generator functionTypedDateprototype { const d = ; if !d return prefix + 'Value cannot be converted to a valid date: ' + value; if thismax && d > thismax return prefix + 'Value must be less than or equal to the max date value.'; if thismin && d < thismin return prefix + 'Value must be greater than or equal to the min date value.'; return null;}; // #5 - define the normalize functionTypedDateprototype { return ;}; // #6 - define the registration directiveTypedDateregister = aliases: 'date' Date dependencies: ; { const d = value instanceof Date ? value : value; return ? undefined : d;}
Finally, we need to register the controller:
const FullyTyped = ;FullyTypedcontrollers;
Controller API
Register
Register a controller with the typed system to enable use of the type. You will need this function if you are including types from other libraries or if you are writing your own typed controller.
Parameters
- controller - A valid controller function as defined in the Write a Plugin section.
Returns undefined.
Typedcontrollers;
Delete
Delete an existing controller.
Parameters
- alias - An alias of the controller you want to delete.
Returns undefined.
Typedcontrollers;
Get
Get an existing controllers data structure.
Parameters
- alias - An alias of the controller you want to get.
Returns null if not found, or an object with the following format:
-
alias - The primary alias name.
-
aliases - An array of all aliases.
-
controller - The primary controller function.
-
controllers - An array of all controllers (including dependency controllers) that make up the controller.
-
errorFunctions - An array of all error functions (including dependency error functions).
-
dependencies - Aliases for all dependencies for this controller.
-
normalizeFunctions - An array of all normalize functions (including dependency error functions).
const data = Typedcontrollers;
Has
Check to see if a controller has been defined with the specified alias.
Parameters
- alias - An alias of the controller you check for.
Returns true
if registered, false
if not registered.
Typedcontrollers;
Is
Check to see if two aliases are referencing the same controller.
Parameters
-
alias1 - The first alias.
-
alias2 - The second alias.
Returns true
if both aliases are for the same controller, otherwise false
.
Typedcontrollers;
List
Get an array of all registered type controllers.
Parameters None
Returns an array of controller data objects.
Typedcontrollers;