Neues Node.js-Buch
Alle Artikel

Check type of callback parameter

Problem

You want to be sure that the value passed as the callback parameter is really a function.

Ingredients

  • the typeof operator
  • the === operator
  • optional: the toString() and the call method

Directions

  1. Given: a function that accepts a callback function.

    function someFunction(callback) {
      callback();
    }
  1. Check that callback is of type function.

    function someFunction(callback) {
      if(typeof callback === 'function') {
        callback();
      }
    }
  2. Optional: otherwise throw an error.

    function someFunction(callback) {
      if(typeof callback === 'function') {
        callback();
      } else {
        // handle it, throw error
        throw new TypeError('The callback parameter is no function.');
      }
    }
  3. Voilá, a delicious type check of the callback parameter.

    someFunction(() => {console.log(4711)});  // 4711
    someFunction({});                         // TypeError

Variants

  • Variant 1: use Object.prototype.toString as well.

    function someFunction(callback) {
      if(Object.prototype.toString.call(callback) === '[object Function]'
        || typeof callback === 'function') {
        callback();
      } else {
        // handle it, throw error
        throw new TypeError('The callback parameter is no function.');
      }
    }

Alternative recipes

  • Use a type checking library like typly (after installing it via npm install typly).

    'use strict';
    const typly = require('typly');
    function someFunction(callback) {
      // only check
      if(typly.isFunction(callback)) {
        callback();
      } else {
        // handle it, throw error
        throw new TypeError('The callback parameter is no function.');
      }
    }
    'use strict';
    const typly = require('typly');
    function someFunction(callback) {
      // check and throw error when necessary
      typly.assertFunction(callback));
      callback();
    }