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 🙏

© 2024 – Pkg Stats / Ryan Hefner

type-enforcement

v1.0.18

Published

Simple and flat class-based typing

Downloads

152

Readme

Type Enforcement

License Build Status Coverage Status Known Vulnerabilities

Examples

Type Enforcement is a js simple and flat library for class-based typing.

Uml diagramm

JavaScript dynamically typed and allows you to declare functions, objects, and variables without declaring a type. Although this feature simplifies the use of the language, it often requires the verification of input data. Type Enforcement helps verify the types of transmitted values on the runtime.

Getting Started

Installation

To use Type Enforcement in your project, run:

npm i type-enforcement

API docs

Table of Contents

class TypeEnforcement

class: TypeEnforcement

Browser-compatible TypeEnforcement class, implemented by following the ECMAScript® 2019 Language Specification standard.

constructor: new TypeEnforcement(shema)

  • shema <Object> An object is an enumeration of rules of the form order : rules <Object>.

In the code there can be more than one validation of the input data, so the rules are grouped into an order.

Except for null and undefined, all primitive values have object equivalents that wrap around the primitive values:

  • String for string primitive.
  • Number for the number of the primitive.
  • Boolean for the boolean primitive.
  • Symbol for Symbol primitive.
  • BigInt for the big number of the primitive.

Therefore, primitives can be declared via an object:

const TypeEnforcement = require('type-enforcement');

const te = new TypeEnforcement({
  primitive: {
    string: String,
    number: Number,
    boolean: Boolean,
    symbol: Symbol
  }
});

NOTE When using a undefined or null, an exception will be thrown.

In addition to primitives, you can use standard built-in objects and custom class, for example:

const TypeEnforcement = require('type-enforcement');

class MyClass {}

const te = new TypeEnforcement({
  inline: {
    object: Object,
    invoke: Function,
    regexp: RegExp,
    array: Array,
    date: Date,
    error: Error,
    promise: Promise
  },
  custom: {
    class: MyClass
  }
});

te.validate(order, values, [options])

  • order <String> scheme name.
  • values <Object> an object is an enumeration of the rules of the form field: value, where field is the name of the value being validate, described in shema.
  • options <Object>
    • skip <Boolean> The skip option allows you to check only part of the values. Default: false.
  • returns: <Error | null>

Unlike the instanceof operator, this method validate if the value of the constructor.prototype rule matches only on the current prototype If all the values of the fields correspond to the scheme, then returns null otherwise returns an error.

const TypeEnforcement = require('type-enforcement');

const te = new TypeEnforcement({
  '#example()': {
    foo: Number,
    bar: Array
  }
});

function example(foo, bar) {
  const err = te.validate('#example()', {
    foo,
    bar
  });

  if (err) {
    throw err;
  }
}

example('1'); // throw Error: Invalid value 'foo' in order '#example()'. Expected Number
example(1); // throw Error: Invalid value 'bar' in order '#example()'. Expected Array
example(1, []); // undefined

The te.validate method is especially useful for implementing default parameters using the capabilities of ECMAScript® 2015 Language Specification standard.

const TypeEnforcement = require('type-enforcement');

const te = new TypeEnforcement({
  '#example()': {
    foo: Number,
    bar: Array
  }
});

function example(foo = 0, bar = []) {
  const err = te.validate('#example()', {
    foo,
    bar
  });

  if (err) {
    throw err;
  }
}

example(); // undefined

This only replaces undefined values with defaults, which is sane. The skip option allows you to check only part of the document, for example:

const TypeEnforcement = require('type-enforcement');

const te = new TypeEnforcement({
  '#example()': {
    foo: Number,
    bar: Array
  }
});

function example(foo, bar) {
  const err = te.validate('#example()', { foo }, { skip: true });
                                          // ↑ 'bar' field is omitted
  if (err) {
    throw err;
  }
}

example('1'); // throw Error: Invalid value 'foo' in order '#example()'. Expected Number
example(1); // undefined

In the example above, the bar field is omitted.

te.normalise(order, values)

  • order <String>
  • values <Object> An object is an enumeration of the rules of the form field: value, where field is the name of the value being validate, described in shema.
  • returns: <Object>

To normalize primitive types, properties of object analogs Primitive(value) are used and a primitive. For other objects, an instance is created with the given value transferred to the constructor.prototype, namely: new Class(value). The following example demonstrates the usefulness of te.normalise(order, values) when using internetwork interoperability of applications.

const values = {
  boo: true,
  now: new Date()
};

const pack = JSON.stringify(values);
// '{"boo":true,"now":"2018-09-26T10:38:08.033Z"}'
//                    ^^^
//                    this is a string type

// ================ interworking ================

const TypeEnforcement = require('type-enforcement');

// Declaring rules
const te = new TypeEnforcement({
  example: {
    boo: Boolean,
    now: Date
  }
});

const json = JSON.parse(pack);
// {boo: true, now: "2018-09-26T10:38:08.033Z"}
//                    ^^^
//                    it's still a string type

const doc = te.normalise('example', json);
// { boo: true, now: 2018-09-26T10:35:41.345Z }
//                    ^^^
//                    this date type

console.log(doc);

The undefined is a property of the global object; i.e., it is a variable in global scope. The initial value of undefined is the primitive value undefined. Note the following example:

Number(undefined); // NaN
Number(); // 0

In the author's opinion, such behavior is useful. The following example will demonstrate this behavior.

const TypeEnforcement = require('type-enforcement');

const te = new TypeEnforcement({
  example: {
    foo: Number,
    bar: String
  }
});

const values = te.normalise(example, {
  foo: undefined,
  bar: undefined
});

console.log(values); // { foo: 0, bar: '' }