是否有一种方法可以让javascript函数知道某个参数是某个类型的?
能够做这样的事情将是完美的:
function myFunction(Date myDate, String myString)
{
//do stuff
}
谢谢你!
更新:作为答案是一个响亮的“不”,如果我想myDate被视为一个日期(为了在它上调用日期函数),我必须将其转换为函数内的日期或设置一个日期类型的新变量?
是否有一种方法可以让javascript函数知道某个参数是某个类型的?
能够做这样的事情将是完美的:
function myFunction(Date myDate, String myString)
{
//do stuff
}
谢谢你!
更新:作为答案是一个响亮的“不”,如果我想myDate被视为一个日期(为了在它上调用日期函数),我必须将其转换为函数内的日期或设置一个日期类型的新变量?
当前回答
不是在JavaScript本身,而是使用谷歌闭包编译器的高级模式,你可以做到:
/**
* @param {Date} myDate The date
* @param {string} myString The string
*/
function myFunction(myDate, myString)
{
//do stuff
}
参见https://code.google.com/closure/compiler/docs/js-for-compiler.html
其他回答
不,JavaScript不是静态类型语言。有时可能需要手动检查函数体中的参数类型。
使用typeof或instanceof:
const assert = require('assert');
function myFunction(Date myDate, String myString)
{
assert( typeof(myString) === 'string', 'Error message about incorrect arg type');
assert( myDate instanceof Date, 'Error message about incorrect arg type');
}
TypeScript是目前最好的解决方案之一。
TypeScript通过向语言中添加类型来扩展JavaScript。
Typescript版本演示
// type alias
type myDateType = Date;
type myStringType = string;
function myFunction(myDate: myDateType, myString: myStringType) {
// do stuff
console.log(`myDate =`, myDate);
console.log(`myString =`, myString);
}
myFunction(new Date(), 'TypeScript is awesome!');
试试这个在线游乐场
refs
https://www.typescriptlang.org/
我也一直在考虑这个问题。从C的背景,你可以模拟函数返回的代码类型,以及参数类型,使用如下:
function top_function() {
var rc;
console.log("1st call");
rc = Number(test_function("number", 1, "string", "my string"));
console.log("typeof rc: " + typeof rc + " rc: " + rc);
console.log("2nd call");
rc = Number(test_function("number", "a", "string", "my string"));
console.log("typeof rc: " + typeof rc + " rc: " + rc);
}
function test_function(parm_type_1, parm_val_1, parm_type_2, parm_val_2) {
if (typeof parm_val_1 !== parm_type_1) console.log("Parm 1 not correct type");
if (typeof parm_val_2 !== parm_type_2) console.log("Parm 2 not correct type");
return parm_val_1;
}
在调用函数之前的Number返回一个Number类型,而不管实际返回值的类型是什么,就像在第二次调用中看到的,其中typeof rc = Number但值是NaN
上面的console.log是:
1st call
typeof rc: number rc: 1
2nd call
Parm 1 not correct type
typeof rc: number rc: NaN
这可以很容易地用ArgueJS完成:
function myFunction ()
{
arguments = __({myDate: Date, myString: String});
// do stuff
};