/jty

A minimal type checking library that I need in various projects for safer programming

Primary LanguageTypeScriptMIT LicenseMIT

JTY Logo

Build Status GitHub issues GitHub forks GitHub stars GitHub license Vulnerabilities Downloads

jty - the tiny JavaScript type checker

A minimalistic library for writing safer code. It came out of a few years of programming JavaScript and TypeScript where I wrote these functions over and over to ensure code reliability.

Fail early with a good error rather than continue with the wrong assumption

  • Minimalistic: complements what's available in JavaScript
  • No dependencies
  • Unified, solid and predictable behavior for all functions:
    • All functions return true or false (none of them throws in any condition)
    • Never mutates any parameter
    • Never throws exceptions
    • Short expressive names to minify better
    • Has short code that's easy to understand and audit
  • Resistent to monkey patching or malicious prototype pollution
  • Comes with TypeScript support out of the box
  • Thoroughly tested for edge cases
  • Works in Node and Browsers (CommonJS out of the box)
  • High performance

jty makes no assumption about how you handle anomalies. You throw an error or use it in conditional statements. This is the bare minimum for type detection, not an assertion library.

👉 See API docs

Why?

  • For JavaScript, jty helps verify function/method contracts and fail early with good error messages instead of continuing on wrong assumption and producing wrong results (which is hard to debug due to implicit type conversion quirks)
  • For TypeScript, jty helps guarantee type safely when called from JavaScript code (also provides reliability against abusing TypeScript's escape hatches like as and any). TypeScript may create a false sense of type safety, specially when interoperating with external systems that are not in TypeScript like APIs or other JavaScript code.
  • For REST APIs, jty helps verify the shape of the API response at response reception §
  • For JSON/YML, jty helps verify the shape of the objects (like configs or manifest.json) inside the code §

§ Technically you can solve these problems with JSON Schema validators, but:

  • It requires learning a DSL instead of using play JavaScript
  • The DSL is parsed at runtime (or compiled to generated JS code beforehand to avoid the performance penalty)
  • Usually relies on externalized specifications as opposed to failing at the location where the data is used (see "Best Practices")

How to use it?

$ npm i jty
// In your JS file
const { isStr } = require('jty')

if (isStr('Hello world!', 3)) {
    console.log('Success')
} else {
    throw new TypeError('Expected an string with at least 3 characters')
}

If you use TypeScript, many of these functions work as type guards:

const a = { foo: 13 }

if (hasPath(a, 'bar', 'baz')) {
  // `a.foo` is valid, as well as `a.bar` and `a.bar.baz`
}

Let's say you have a function that is supposed to double a number:

function double(n) {
    return n + n
}
double(1)  // 2
double(13) // 26

But this function happily accepts strings which is not desired:

double('13') // '1313'

Using jty we can verify the input before using it:

const { isNum } = require('jty')

function double(n) {
    if (isNum(n)) {
        return n + n
    }
    throw new TypeError(`Expected a number but got ${n}`)
}

double(13)   // 26
double('13') // throws 'Expected a number but got 13'
double(NaN)  // throws 'Expected a number but got NaN'

You can also use the assertion library of your choice to make the code shorter and more readable:

// Node assert: https://nodejs.org/api/assert.html
const assert = require('assert')
const { isNum } = require('jty')

function double(n) {
    assert(isNum(n), 'double() number input')
    return n + n
}

API

On Github Pages

Best practices

On the wiki


Made in Sweden 🇸🇪 by Alex Ewerlöf