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.of

v1.3.6

Published

Effective type checking in plain javascript.

Downloads

13

Readme

Effective type checking in plain javascript.

npm install type.of

Expressive syntax:

function person(name, weight, children) {

  TYPEOF
    (...arguments)
    (String, Number, Array)

  // ...
}

Nice messages:

TypeError:

    (2) required: number
        Provided: string

    (3) required: array
        Provided: { name:string, weight:number, children:array }

    at yourFunction (/Users/.../yourFile.js:10:7)
    at /Users/.../yourFile.js:13:3
    at Object.<anonymous> (/Users/.../yourFile.js:15:2)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    ...

Javascript is hostile to effective type checking.

typeof null               // object   >:(

typeof NaN                // number   :?

NaN === NaN               // false    >:(

typeof [1, 2]             // object   >:(

's' instanceof String     // false    :/

5 instanceof Number       // false    :/

true instanceof Boolean   // false    :/

Gotchas make manual type validation logic categorically unmaintainable. And even if it were maintainable, thorough checks are grotesque. TYPEOF reduces all this to rote declaration:

function person(name, weight, children) {

  TYPEOF
    (...arguments)
    (String, Number, Array)

  // ...
}

We fix the gotchas, and when mismatches happen, there's no detective work:

TypeError:

    (2) required: number
        provided: string

    at yourFunction (/Users/.../yourFile.js:10:7)
    at /Users/.../yourFile.js:13:3
    at Object.<anonymous> (/Users/.../yourFile.js:15:2)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    ...

API

Validate types.

TYPEOF implements pairwise type validation with Curry syntax:

TYPEOF(val1, ..., valN)(type1, ..., typeN)

So, validating a single value is just the limiting case:

function isYoung(age) {

  TYPEOF(age)(Number)

  return age < 80
}

Array-like iterables (i.e., arrays and native arguments objects) can be validated concisely using the spread operator, as follows:

function example(name, age, isTall) {

  TYPEOF
    (...arguments)
    (String, Number, Boolean)

  // Do stuff.
}

Type validation calls return the first value passed, so function return types can be validated easily:

function divide(num1, num2) {
  return TYPEOF(num1 / num2)(Number)
}

divide(10, 2) // returns 5

divide(10, undefined) // throws

Type descriptions

Native and custom types work.

TYPEOF(val)(ArrayBuffer)
TYPEOF(val)(MyClass)
TYPEOF(val)('MyClass') // <-- By name works too.

Duck types work.

Specify any subset of keys and corresponding types to duck type a value.

TYPEOF
  (val)
  ({ name:String, weight:Number })

TypeErrors produce description diffs of the form:

TypeError:

    (1) required: { name:string, weight:number, ... }
        provided: { name:number, weight:string, ... }

    ...

Disjoint types work.

Use arrays to express that any of the given types is valid.

TYPEOF(val)([String, Number])

TypeErrors produce description diffs of the form:

TypeError:

    (1) required: string|number
        provided: null

    ...

You can declare 'void' and 'any'.

function example() {

  TYPEOF
    (...arguments)
    ('void')

  // Do whatever.
}

Or permit any type:

TYPEOF(val)('any')

Mix and nest as necessary.

TYPEOF
  (...arguments)
  ([MyClass, String], { prop:MyClass, prop2:'any' }, 'MyClass')

Defined types keep you DRY.

Define complex types with TYPEOF.DFN() for DRY-ness and concision. Here we'll describe the signature of a middleware function:

TYPEOF.DFN('req', { originalUrl:String, method:String })
TYPEOF.DFN('res', { headersSent:Boolean, locals:Object })

And we can use it anywhere:

// ./some-middleware.js
function myMiddleware(req, res, next) {

  TYPEOF
    (...arguments)
    ('req', 'res', Function)

  // Do whatever...
}

It's powerfully wily. You can define functions to check types when you need to do something weird, like check that a value isn't of a particular type, for example:

TYPEOF.DFN('not Object', val => !(val instanceof Object), true)

TYPEOF({})('not Object') // throws

Passing true as the third parameter tells TYPEOF that the notObject function should be invoked to check the type, taking the value being checked as the sole argument.

Warn mode.

Use TYPEOF.WARN() to have TYPEOF merely report TypeErrors in the console. (This is useful when refactoring.)

Off.

TYPEOF.OFF() Disables all type checking, eliminates the (negligible) performance hit of the type checks, and prevents throw-ing. (This is useful in production.)

React to TypeErrors

Call TYPEOF.ONFAIL(callback) and pass a callback to implement remote logging (or whatever). When an error is encountered, it will be passed to your function.