Editar: Siete años después, esta respuesta todavía recibe votos positivos ocasionales. Está bien si está buscando la verificación en tiempo de ejecución, pero ahora recomendaría la verificación de tipos en tiempo de compilación usando TypeScript o posiblemente Flow. Ver https://stackoverflow.com/a/31420719/610585 arriba para obtener más información.
Respuesta original:
No está integrado en el lenguaje, pero puede hacerlo usted mismo con bastante facilidad. La respuesta de Vibhu es lo que consideraría la forma típica de verificación de tipos en Javascript. Si desea algo más generalizado, intente algo como esto: (solo un ejemplo para comenzar)
typedFunction = function(paramsList, f){
//optionally, ensure that typedFunction is being called properly -- here's a start:
if (!(paramsList instanceof Array)) throw Error('invalid argument: paramsList must be an array');
//the type-checked function
return function(){
for(var i=0,p,arg;p=paramsList[i],arg=arguments[i],i<paramsList.length; i++){
if (typeof p === 'string'){
if (typeof arg !== p) throw new Error('expected type ' + p + ', got ' + typeof arg);
}
else { //function
if (!(arg instanceof p)) throw new Error('expected type ' + String(p).replace(/\s*\{.*/, '') + ', got ' + typeof arg);
}
}
//type checking passed; call the function itself
return f.apply(this, arguments);
}
}
//usage:
var ds = typedFunction([Date, 'string'], function(d, s){
console.log(d.toDateString(), s.substr(0));
});
ds('notadate', 'test');
//Error: expected type function Date(), got string
ds();
//Error: expected type function Date(), got undefined
ds(new Date(), 42);
//Error: expected type string, got number
ds(new Date(), 'success');
//Fri Jun 14 2013 success