Anderson Green Anderson Green - 29 days ago 8
Javascript Question

Checking the types of function arguments in Javascript

In Javascript, is there any way to check the types of a function's arguments? I want to write a function called

checkTypes
that does the following:

function checkTypes(typeArr){
//if the types do not match typeArr, throw an error
}

function exampleUsage(arr1, arr2, num1){
checkTypes("object", "object", "number");
//throw an error if the types do not match the corresponding elements
}

Answer

You can use the the typeOf function adapted from this post Fixing the JavaScript typeof operator combined with this function:

function typeOf( obj ) {
  return ({}).toString.call( obj ).match(/\s(\w+)/)[1].toLowerCase();
}

function checkTypes( args, types ) {
  args = [].slice.call( args );
  for ( var i = 0; i < types.length; ++i ) {
    if ( typeOf( args[i] ) != types[i] ) {
      throw new TypeError( 'param '+ i +' must be of type '+ types[i] );
    }
  }
}

function foo( a,b,c ) {
  checkTypes( arguments, ['string', 'number', 'array'] );
  return 'foo';
}

console.log( foo( 'a', 1, [2] ) ); //=> foo
console.log( foo( 1, 1, [2] ) ); 
//^ Uncaught TypeError: param 0 must be of type string