在Javascript中检查函数参数的类型

And*_*een 8 javascript

在Javascript中,有没有办法检查函数参数的类型?我想编写一个名为的函数checkTypes,它执行以下操作:

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
}
Run Code Online (Sandbox Code Playgroud)

elc*_*nrs 12

您可以使用typeOf从此文章改编的函数修复JavaScript typeof运算符并结合此函数:

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
Run Code Online (Sandbox Code Playgroud)


dav*_*ers 9

typeof在这种情况下不要使用.由于以下几个原因,这有问题:

typeof null                 // 'object'
typeof []                   // 'object'
typeof 'foo'                // 'string'
typeof new String('foo')    // 'object'
'foo' == new String('foo')  // true
Run Code Online (Sandbox Code Playgroud)

相反,使用Object::toString:

Object.prototype.toString.call(null)               // '[object Null]'
Object.prototype.toString.call([])                 // '[object Array]'
Object.prototype.toString.call('foo')              // '[object String]'
Object.prototype.toString.call(new String('foo'))  // '[object String]'
Run Code Online (Sandbox Code Playgroud)

装饰者会满足您的要求:

var getType = function(value) {
  return Object.prototype.toString.call(value)
    .replace(/^\[object |\]$/g, '').toLowerCase();
};

var checkTypes = function(types, fn) {
  return function() {
    var args = Array.prototype.slice.call(arguments, 0);
    for (var idx = 0; idx < types.length; idx += 1) {
      var expected = types[idx];
      var received = getType(args[idx]);
      if (received != expected) {
        throw new TypeError('expected ' + expected + '; received ' + received);
      }
    }
    fn.apply(null, args);
  };
};

var exampleUsage = checkTypes(['array', 'array', 'number'], function(arr1, arr2, num1) {
  console.log('arr1:', arr1);
  console.log('arr2:', arr2);
  console.log('num1:', num1);
});
Run Code Online (Sandbox Code Playgroud)

用法示例:

exampleUsage([], [], 0);
// arr1: []
// arr2: []
// num1: 0

exampleUsage([], [], 'foo');
// TypeError: expected number; received string
Run Code Online (Sandbox Code Playgroud)