@bemoje/assert-type
Perform easy type-checks with a simple type assertion.
Version
Travis CI
Dependencies
Stats
Donate
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