deep-type-check

Runtime type checking with "value as type" model definition in Javascript.

Usage no npm install needed!

<script type="module">
  import deepTypeCheck from 'https://cdn.skypack.dev/deep-type-check';
</script>

README

deep-type-check

Build Status NPM Version

Runtime type deep-checking with value as type model definition in Javascript.

Installation

npm i deep-type-check 

Motivation

Runtime type checking in Javascript has always been a pain-point even for some veterans. With the help of Typescript type annotation, and some modern Javascript feature such as optional chaining, this issue has been alleviated . But for some cases, there is still no simple way. For instance:

interface User {
  name: string;
  hobby: string[];
}

const { body } = await fetch('/user/:id')
// body = { "name": "peter", hobby: "badminton" }

const user: User = JSON.parse(body)

user.hobby.forEach((h) => { console.log(h) })
// Uncaught TypeError: user.hobby.forEach is not a function

We can have everything concretely typed throughout our code-base, but response from API is always a risk to break our app at runtime. To secure our app at runtime, we might do something like below, the more properties we want to check, the more tedious code we need to write.

// runtime type checking
if (user.hobby instanceof 'Array') {
  user.hobby.forEach(() => {})
} else {
  throw 'not good response from API'
}

What if we can do something like this?

if (check(userModel, userData)) {
    
}

Quick Start

Declare runtime model definition using value as type. The non-currying way:

import { check } from 'deep-type-check'

const modelA = {
    foo: 0              // number type
}

const modelB = {
    foo: ''             // string type
}

const data = {
    foo: 3.14
}

check(modelA, data)     // => true
check(modelB, data)     // => false 

The currying way:

const data = {
    foo: 3.14
}

const typeCheckerA = check({ foo: 0 })
const typeCheckerB = check({ foo: '' })

typeCheckerA(data)      // => true
typeCheckerB(data)      // => false

Usage

Pass whatever type you want to check.

check('', '')           // => true 
check(null, '')         // => false
check(undefined, '')    // => false
check(1, '')            // => false
check(true, '')         // => false
check([], '')           // => false 
check({}, '')           // => false

Required

All object properties declared are required by default.

const model = { a: 1 }

check(model, {})        // => false, missing property "a"

Optional

Making property optional.

import { check, optional } from "deep-type-check";

const model = { a: optional(1) }

check(model, {})        // => true, property "a" is optional

Or you can just mark a type as optional.

check(optional(1), undefined)
// => true

Making null or undefined optional does not make sense, so:

check({ a: optional(null) })
// => Error 'optional does not accept null or undefined'

Any type

For any type, use the magic string any.

check('any', null)                // => true
check('any', undefined)           // => true
check('any', 1)                   // => true
check('any', '')                  // => true
check('any', true)                // => true
check('any', [])                  // => true
check('any', {})                  // => true
check({ a: 'any' }, { a: 1 })     // => true
check({ a: 'any' }, { a: '' })    // => true
check(['any'], [1])               // => true
check(['any'], ['1'])             // => true

Recursive vs non-recursive

Function check will do the deep-check by default. Using the shallowCheck for non-recursive mode.

import { check, shallowCheck } from 'deep-type-check'

check([[1]], [['1']])
// => false, type mismatch of nested array

check({
    a: { b: 1 }
}, {
    a: { b: '1' }
})
// => false, type mismatch of nested object

shallowCheck([[1]], [['1']])
// => true, shallow check won't go recursively

shallowCheck({
    a: { b: 1 }
}, {
    a: { b: '1' }
})
// => true, shallow check won't go recursively

Array with multiple types

A similar implementation to the tuple type in Typescript.

// the array accept both number and string as its item's type

check([1, ''], ['foo'])     // => true
check([1, ''], [9])         // => true
check([1, ''], [9, 'foo'])  // => true
check([1, ''], ['foo', 9])  // => true