@bemoje/throw-type-error

Throws a TypeError with a generated error message with ANSI-colors for easier console output readability.

Usage no npm install needed!

<script type="module">
  import bemojeThrowTypeError from 'https://cdn.skypack.dev/@bemoje/throw-type-error';
</script>

README

@bemoje/throw-type-error

Throws a TypeError with a generated error message with ANSI-colors for easier console output readability.

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/throw-type-error
npm install --save @bemoje/throw-type-error
npm install --save-dev @bemoje/throw-type-error

Usage

import throwTypeError from '@bemoje/throw-type-error'

import throwTypeError from '../src/throw-type-error'

/**
 * Adds a and b
 * @param {number} a - The first number
 * @param {number|string} b - The second number, or a number coercible-string
 */
function add(a, b) {
    // type check 'a'
    if (!isType(Number, a)) {
        throwTypeError(Number, a)
    }

    // type check 'b'
    if (!isType(Number, b) && !isType(String, b)) {
        throwTypeError([Number, String], b)
    }

    // coerce b
    b = Number(b)

    // add
    return a + b
}

add(1, 2)
//=> 3

add(1, '2')
//=> 3

add('one', 2)
//=> throws TypeError('Expected Number, got String) [IN ANSI COLORED FOR READABILITY]

add(1, /2/g)
//=> throws TypeError('Expected [Number, String], got RegExp) [IN ANSI COLORED FOR READABILITY]

Tests

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

npm run test

API

throwTypeError

Throws a TypeError with a generated error message with ANSI-colors for easier console output readability.

Parameters
  • expectedTypeConstructor function The expected type's constructor

  • value any The value to evaluate

Returns

void