@bemoje/assert-type

1.0.1 • Public • Published

@bemoje/assert-type

Perform easy type-checks with a simple type assertion.

Version

NPM version

Travis CI

dependencies

Dependencies

dependencies

Stats

NPM downloads Forks

Donate

Buy Me A Beer donate button PayPal donate button

Installation

npm install @bemoje/assert-type
npm install --save @bemoje/assert-type
npm install --save-dev @bemoje/assert-type

Usage

import assertType from '@bemoje/assert-type'

/**
 * @param {string} str
 * @param {number} num
 * @param {null} nul
 * @param {number|string} strOrNum
 */
function example(str, num, nul, strOrNum) {
	// quite extensive, but now very simple type-checks.
	assertType(String, str)
	assertType(Number, num)
	assertType(null, nul)
	assertType([String, Number], strOrNum)

	// other code
	return 'Types are checked and OK'
}

const STRING = 'a'
const NUMBER = 1
const ARRAY = []

// NOTE: 'undefined' always passes type check

example()
//=> 'Types are checked and OK'

example(STRING, NUMBER, null, STRING)
//=> 'Types are checked and OK'

example(STRING, NUMBER, null, NUMBER)
//=> 'Types are checked and OK'

example(ARRAY, NUMBER, null, STRING)
//=> throws TypeError('Expected String, got Array')

example(STRING, ARRAY, null, STRING)
//=> throws TypeError('Expected Number, got Array')

example(STRING, NUMBER, ARRAY, STRING)
//=> throws TypeError('Expected Null, got Array')

example(STRING, NUMBER, null, ARRAY)
//=> throws TypeError('Expected String, Number, got Array')

Tests

Uses Jest to test module functionality. Run tests to get coverage details.

npm run test

API

assertType

Perform easy type-checks with a simple type assertion.

Parameters
  • constructors (function | null | Array<(function | null)>) The expected type's constructor(s). Also accepted as a "constructor" is the null value.

  • value any The value to evaluate

Returns

void

Package Sidebar

Install

npm i @bemoje/assert-type

Weekly Downloads

12

Version

1.0.1

License

MIT

Unpacked Size

11.5 kB

Total Files

5

Last publish

Collaborators

  • bemoje