Skip to content

ericfortis/type-value-checker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

type-value-checker

A plain-JS type checker with an API similar to:

Single type definition

import { check } from 'type-value-checker'

check([], Array)
check('a', String)
check(100, Number)
check(new Int8Array([1, 2, 3]), Int8Array)

The value is returned, as well:

const t_num = n => check(n, Number)
function square(n) {
  t_num(n)
  return t_num(n * n)
}

Multiple type definitions

import { check, Where, Optional, OptionalWhere, Shape } from 'type-value-checker'

function Person(p) {
  check(p, {
    name: String,
    age: Where(Number.isInteger),
    nick: Optional(String),
    zipcode: OptionalWhere(isValidZipCode),
    point: Shape({ 
      x: Number, 
      y: Number
    })
  })
  
  this.name = p.name
  this.age = p.age
  this.nick = p.nick || ''
  this.zipcode = p.zipcode || null
  this.point = p.point
}

function isValidZipCode(zip) {
  return /^\d{5}$/.test(zip)
}
new Person({ name: 'John' }) 
// Throws `TypeError` because only `nick` and `zipcode` are optional.
new Person({ unspecified: true }) 
// Throws `TypeError` because `unspecified` is not 
// type-defined and it's missing required fields.

About

Runtime type and value checking

Resources

License

Stars

Watchers

Forks