npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

typic

v1.2.2

Published

Type and schema validation

Readme

Motivation

Typic is a validator for Javascript/Typescript variables and objects, very much like Hapijs's JOI. As a matter of fact JOI has been the model for Typic in many respects.

There are more object validation tools for JS than one can count, and now we have one more. The main motivation for Typic was to create a validator tool that

  1. returns the errors following the structure of the tested object (even for nested objects)
  2. returns every error (eager validation - when it makes sense)
  3. returns the passed values of the tested object keeping the structure
  4. provides tools for logical combinations (AND, NOT, OR)

Read on for a quick introduction or head to the exciting COOKBOOK or read the API description. Throughout the documentation you will find TypeScript type definitions attached to the explanations.

Usage

yarn add typic
const validator = require("typic").default;
import validator from "typic";

const schema = validator()
  .string()
  .minLength(8)
  .maxLength(64)
  .hasUppercase()
  .hasNumber();

const result = schema.validate("Password1");
validator()     // 1)  creates a new Schema (an AnySchma to be precise)
.string()       // 2)  specifies the expected type (e.g. number, string, array, json)
.minLength(8)   // 3+) specifies the expected property that is relevant to the type...
.maxLength(64)
.hasUppercase()
.hasNumber();

Every validation returns a valid, an errors and a passed field:

const result: {
  valid: boolean; // indicates whether the validation was successful
  errors: { [key: string]: any[] } | undefined; // contains error messages
  passed: T | Partial<T> | undefined; // holds the value(s) that passed the validation
};

For primitive types

For primitive types, the error object contains only the "" field with the relevant error messages in an array.

If there is an error (even in array or object validations), the "" field always contains one or more error messages. The reason for using "" instead of accessing error messages directly is to standardize the structure of the error object. As a result, it doesn't matter if the validated element is a number or an object, if the validation fails, the "" field will hold some relevant messages. This means that the same logic can be used to access the error message for primitive and complex types as well.

The result object has also an extra passed field containing value that have matched the criteria. For primitive types, it is most useful when you allow the validator to cast the value if it is of the wrong type.

Let's see a few examples:

const result: {
  valid: boolean;
  errors: {
    "": any[];
  };
  passed: T | undefined; // string | number | undefined
};
import validator from "typic";

const schema = validator()
  .number("Not a number") /* Error messages are optional */
  .min(0, "Should be at least 0")
  .max(10, "Should be at most 10")
  .prime("Should be a prime");
let result;

result = schema.validate("");
/*
  {
    valid: false,
    errors: {
      "": ["Not a number!"]
    },
    passed: undefined
  }
*/

result = schema.validate(-1);
/*
  {
    valid: false,
    errors: {
      "": ["Should be at least 0", "Should be a prime"]
    },
    passed: undefined
  }
*/

result = schema.validate(0);
/*
  {
    valid: false,
    errors: {
      "": ["Should be a prime"]
    },
    passed: undefined
  }
*/

result = schema.validate(2);
/*
  {
    valid: true,
    errors: undefined,
    passed: 2
  }
*/

Primitive types with schemas are:

For complex types

Array

For Array types, the error object contains a "" field with error messages relevant for the entire array, and also "<index>" fields with error messages relevant for the given element. The relevant error messages are the result of other validations and as such they have the same structures as we have seen before.

The result object contains also the passed field containing the elements that have matched the criteria.

const result: {
  valid: boolean;
  errors: {
    "": any[];
    [key: string]: {};
  };
  passed: [];
};
import validator from "typic";

const schema = validator()
  .array()
  .minLength(2)
  .each(
    validator()
      .number()
      .min(0)
      .max(10)
  );
let result;

result = schema.validate({});
/*
  { 
    valid: false,
    errors: { 
      "": [ 
        "Value is not an array!"
      ] 
    },
    passed: undefined   // <- the validated element is not an array, so we got nothing
  }
*/

result = schema.validate([]);
/*
  { 
    valid: false,
    errors: { 
      "": [ 
        "Array should have at least 2 elements!"
      ]
    },
    passed: []  // <- the validated element really is an array, so at least we got that
  }
*/

result = schema.validate([0, -2, 1]);
/*
  {
    valid: false,
    errors: {
      "": [
        "Array elements should satisfy the 'each' condition!"
      ],
      "1": {
        "": [
          "Value should be 0 at least!"
        ]
      }
    },
    passed: [   // <- the values 0 and 1 passed the validation, so we see them in this field
      0,
      null,
      1
    ]
  }
*/

result = schema.validate([0, 2, 1]);
/*
  {
    valid: true,
    errors: {},
    passed: [
      0,
      2,
      1
    ]
  }

*/

Object

Object type validator is called JSON, because it accepts Javascript Objects and JSON strings as well. Because arrays are objects, a json() validator can be used against them as well.

Just as with arrays, the error object contains a "" field with error messages relevant for the entire object, and also "<fieldname>" fields with error messages relevant for the respective field. The result object also contains an extra passed field containing the elements that have matched the criteria.

const schema = validator()
  .json()
  .keys({
    email: validator()
      .string()
      .regex(/\@/), // I know, I know...
    password: validator()
      .string()
      .minLength(8)
      .hasUppercase(),
  });
let result;

result = schema.validate(0);
/*
  {
    valid: false,
    errors: {
      "": [
        "Value is not a JSON!"
      ]
    },
    passed: undefined
  }
*/

result = schema.validate([]);
/*
  {
    valid: false,
    errors: {
      "email": {
        "": [
          "Value is not a string!"
        ]
      },
      "password": {
        "": [
          "Value is not a string!"
        ]
      },
      "": [
        "JSON doesn't match key schema!"
      ]
    },
    passed: {}
  }
*/

result = schema.validate({});
/*
  {
    valid: false,
    errors: {
      "email": {
        "": [
          "Value is not a string!"
        ]
      },
      "password": {
        "": [
          "Value is not a string!"
        ]
      },
      "": [
        "JSON doesn't match key schema!"
      ]
    },
    passed: {}
  }
*/

result = schema.validate({
  email: "[email protected]",
  password: "abcd",
});
/*
  {
    valid: false,
    errors: {
      password: {
        "": [
          "Value should be at least 8 characters long!",
          "Value should contain an uppercase character!'"
        ]
      },
      "": [
        "JSON doesn't match key schema!"
      ]
    },
    passed: {
      email: "[email protected]"
    }
  }

*/

result = schema.validate({
  email: "[email protected]",
  password: "Password1",
});
/*
{
  valid: true,
  errors: undefined,
  passed: {
    email: "[email protected]",
    password: "Password1"
  }
}
*/

For 'any' type

Calling the validator factory validator() return an AnySchema. There the following methods are available:

Apart from the typed schemas, three logical functions are available too on an AnySchema:

  • and(options) -> instructs the AnySchema to validate only if every option validates
  • or(options) -> instructs the AnySchema to validate only if some option validates
  • not(option) -> instructs the AnySchema to validate only if the option does not validate

After calling and, or or not these functions become unavailable, i.e. one AnySchema can validate only in one of these modes.

// Validates only if the value is either a string or a number
const schema = validator().or([validator().string(), validator().number()]);

// Validates only if the array has only string values and its length is divisible by 3
const schema = validator().and([
  validator()
    .array()
    .each([validator().string()]),
  validator()
    .json()
    .keys({
      length: validator()
        .number()
        .multipleOf(3),
    }),
]);

const schema = validator()
  .or([validator().string(), validator().number()])
  .and(/*...*/); // `and` is not available when using types
// also force-calling and() is ineffective

And that is the gist of it.