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

deep-type-check

v1.0.2

Published

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

Downloads

27

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