Problem
You want to be sure that the value passed as the callback parameter is really a function.
Ingredients
- the
typeofoperator - the
===operator - optional: the
toString()and thecallmethod
Directions
-
Given: a function that accepts a callback function.
function someFunction(callback) { callback(); }
-
Check that callback is of type function.
function someFunction(callback) { if(typeof callback === 'function') { callback(); } } -
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.'); } } -
Voilá, a delicious type check of the callback parameter.
someFunction(() => {console.log(4711)}); // 4711 someFunction({}); // TypeError
Variants
-
Variant 1: use
Object.prototype.toStringas 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(); }