Last Updated: February 25, 2016
·
940
· jeroen_ransijn

Use strong typed functions in JavaScript (sort of)

View the gist here.

Note: no support for return type, although this would be quite simple I think

function typed (types, cb) {
  if (Object.prototype.toString.call(types) === '[object Array]' && typeof cb === "function") {
    return function () {
      var i = arguments.length, areTypesCorrect = true;

      while (i--) {
        // need to check for some literals: string/number/boolean
        var type = typeof arguments[i], arg;

        if (type === 'string') {
          arg = new String();
        } else if (type === 'number') {
          arg = new Number();
        } else if (type === 'boolean') {
          arg = new Boolean();
        } else {
          arg = arguments[i];
        }

        if ( ! (arg instanceof types[i]) ) {
          areTypesCorrect = false;
          throw new TypeError('Argument '+ (i+1) + ' "' + arguments[i] + '" is not an instance of "' + types[i] + '" ');
          break;
        }
      }

      areTypesCorrect && cb.apply(this, arguments);
    }
  } else {
    throw new TypeError('(typed): arguments given are not valid');
  }
}

// write your function like this
var myTypedFunction = typed([String, Array], function(str, arr) {
  console.log(str, arr)
});


// will work
myTypedFunction('hello', ['world']);

// will not work
myTypedFunction(false, ['world']);

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside