แก้ไข: เจ็ดปีต่อมาคำตอบนี้ยังได้รับ upvotes เป็นครั้งคราว ไม่เป็นไรถ้าคุณกำลังมองหาการตรวจสอบรันไทม์ แต่ตอนนี้ฉันอยากจะแนะนำการตรวจสอบเวลาแบบคอมไพล์โดยใช้ Typescript หรือ Flow ดูhttps://stackoverflow.com/a/31420719/610585ด้านบนสำหรับข้อมูลเพิ่มเติม
คำตอบเดิม:
มันไม่ได้สร้างไว้ในภาษา แต่คุณสามารถทำได้ด้วยตัวคุณเองอย่างง่ายดาย คำตอบของ Vibhu คือสิ่งที่ฉันจะพิจารณาวิธีการตรวจสอบชนิดทั่วไปใน Javascript หากคุณต้องการสิ่งที่เป็นรูปธรรมมากขึ้นลองทำดังนี้: (แค่ตัวอย่างเพื่อให้คุณเริ่มต้น)
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