Assert-style non-intrusive type checking.


100.0.43 years ago4 years agoMinified + gzip package size for @foko/type-check in KB


type-check Build Status codecov Greenkeeper badge

Assert-style non-intrusive type checks.


It works similar to assert() where you simply state what should happen and then continue to operate. If the type check fails, a valid TypeError is thrown and your function will halt.

Simple example:

function add (a, b) {
  typeCheck('number', a)
  typeCheck('number', b)

  return a + b

add(1, 1) // returns 2
add('1', 1) // throws TypeError
add('1') // throws TypeError
add(1) // throws TypeError
// etc.

Available Types

Type detection is handled by type-detect by the lovely team over at chaijs. If you would like to use your own type detection, you can swap it out by replacing the function at typeCheck.typeOf:

const typeCheck = require('@karimsa/type-check')

// this replaces the type-detect typeOf function with just a native
// use of typeof (which is faster but less useful)
typeCheck.typeOf = function (value) {
  return typeof value

If you would like to make types optional (i.e. the type, undefined, or null) - just append ? to the end of the type name.

Example with optional types:

// all valid
typeCheck('number?', 2)
typeCheck('number?', undefined)
typeCheck('number?', null)

// invalid
typeCheck('number?', '2')


Licensed under MIT license.

Copyright © 2018-present Foko Inc. All rights reserved.

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.