有没有办法让javascript函数知道某个参数属于某种类型?
能够做这样的事情将是完美的:
function myFunction(Date myDate, String myString)
{
//do stuff
}
谢谢!
更新:答案是肯定的“否”,如果我想myDate
被视为日期(以便在其上调用日期函数),则必须将其强制转换为日期在函数内或设置一个新变量输入日期吗?
不,JavaScript不是静态类型的语言。有时您可能需要手动检查函数主体中的参数类型。
不使用JavaScript本身,而是使用Google Closure Compiler的高级模式,您可以这样做:
/**
* @param {Date} myDate The date
* @param {string} myString The string
*/
function myFunction(myDate, myString)
{
//do stuff
}
请参阅http://code.google.com/closure/compiler/docs/js-for-compiler.html
虽然您无法向JavaScript告知有关类型的语言,但是可以向您的IDE告知它们有关类型的信息,因此您可以获得更多有用的自动完成功能。
有两种方法可以做到这一点:
-
使用JSDoc,该系统用于在注释中记录JavaScript代码。特别是,您将需要以下
@param
指令:/** * @param {Date} myDate - The date * @param {string} myString - The string */ function myFunction(myDate, myString) { // ... }
您还可以使用JSDoc定义自定义类型,并在
@param
指令中指定自定义类型,但请注意,JSDoc不会进行任何类型检查。它只是一个文档工具。要检查JSDoc中定义的类型,请查看TypeScript,它可以解析JSDoc标签。 -
通过在类型中的参数之前指定类型来使用类型提示
/* comment */
:这是一种相当普遍的技术,例如被ReactJS使用。对于传递给第三方库的回调参数非常方便。
打字稿
对于实际的类型检查,最接近的解决方案是使用TypeScript(一种(主要是)JavaScript的超集)。这是5分钟内的TypeScript。
从Facebook中检查新的Flow库,“静态类型检查器,旨在在JavaScript程序中查找类型错误”
定义:
/* @flow */
function foo(x: string, y: number): string {
return x.length * y;
}
foo('Hello', 42);
类型检查:
$> flow
hello.js:3:10,21: number
This type is incompatible with
hello.js:2:37,42: string
这是如何运行它。
您可以使用功能中的包装器来实现一个自动处理类型检查的系统。
使用这种方法,您可以构建一个完整的文件
declarative type check system
,该文件将为您管理类型检查。如果您有兴趣更深入地了解此概念,请检查Functyped库
以下实现以简单但可操作的方式说明了主要思想:
/*
* checkType() : Test the type of the value. If succeds return true,
* if fails, throw an Error
*/
function checkType(value,type, i){
// perform the appropiate test to the passed
// value according to the provided type
switch(type){
case Boolean :
if(typeof value === 'boolean') return true;
break;
case String :
if(typeof value === 'string') return true;
break;
case Number :
if(typeof value === 'number') return true;
break;
default :
throw new Error(`TypeError : Unknown type provided in argument ${i+1}`);
}
// test didn't succeed , throw error
throw new Error(`TypeError : Expecting a ${type.name} in argument ${i+1}`);
}
/*
* typedFunction() : Constructor that returns a wrapper
* to handle each function call, performing automatic
* arguments type checking
*/
function typedFunction( parameterTypes, func ){
// types definitions and function parameters
// count must match
if(parameterTypes.length !== func.length) throw new Error(`Function has ${func.length} arguments, but type definition has ${parameterTypes.length}`);
// return the wrapper...
return function(...args){
// provided arguments count must match types
// definitions count
if(parameterTypes.length !== args.length) throw new Error(`Function expects ${func.length} arguments, instead ${args.length} found.`);
// iterate each argument value, and perform a
// type check against it, using the type definitions
// provided in the construction stage
for(let i=0; i<args.length;i++) checkType( args[i], parameterTypes[i] , i)
// if no error has been thrown, type check succeed
// execute function!
return func(...args);
}
}
// Play time!
// Declare a function that expects 2 Numbers
let myFunc = typedFunction( [ Number, Number ], (a,b)=>{
return a+b;
});
// call the function, with an invalid second argument
myFunc(123, '456')
// ERROR! Uncaught Error: TypeError : Expecting a Number in argument 2
不,相反,您需要根据自己的需要执行以下操作:
function myFunction(myDate, myString) {
if(arguments.length > 1 && typeof(Date.parse(myDate)) == "number" && typeof(myString) == "string") {
//Code here
}
}
编辑:七年后,这个答案仍然偶尔得到支持。如果您正在寻找运行时检查,那很好,但是我现在建议使用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
可以使用ArgueJS轻松实现:
function myFunction ()
{
arguments = __({myDate: Date, myString: String});
// do stuff
};
使用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。
https://www.typescriptlang.org/
也许像这样的辅助功能。但是,如果您发现自己经常使用此类语法,则应该切换到Typescript。
function check(caller_args, ...types) {
if(!types.every((type, index) => {
if(typeof type === 'string')
return typeof caller_args[index] === type
return caller_args[index] instanceof type;
})) throw Error("Illegal argument given");
}
function abc(name, id, bla) {
check(arguments, "string", "number", MyClass)
// code
}
我也一直在考虑这个。在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
文章标签:function , javascript
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!