dmr*_*dmr 133 javascript function
有没有办法让javascript函数知道某个参数属于某种类型?
能够做这样的事情是完美的:
function myFunction(Date myDate, String myString)
{
//do stuff
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
更新:由于答案是响亮的"不",如果我想myDate被视为日期(为了在其上调用日期函数),我必须将其作为日期在函数内部或者设置一个新的变量输入日期吗?
pro*_*vit 146
不,JavaScript不是静态类型语言.有时您可能需要手动检查函数体中的参数类型.
eol*_*son 71
不是javascript它自己但使用Google Closure Compiler的高级模式你可以这样做:
/**
* @param {Date} myDate The date
* @param {string} myString The string
*/
function myFunction(myDate, myString)
{
//do stuff
}
Run Code Online (Sandbox Code Playgroud)
请参阅http://code.google.com/closure/compiler/docs/js-for-compiler.html
Dan*_*scu 55
虽然您无法通知JavaScript 有关类型的语言,但您可以向IDE通知它们,以便您获得更多有用的自动完成功能.为此,请通过在以下参数中指定参数之前的类型来使用类型提示@param:

这是一种非常普遍的技术,例如ReactJS使用的技术.对于传递给第三方库的回调参数非常方便.
Ren*_*aud 21
从Facebook 查看新的Flow库,"一个静态类型检查器,旨在查找JavaScript程序中的类型错误"
定义:
/* @flow */
function foo(x: string, y: number): string {
return x.length * y;
}
foo('Hello', 42);
Run Code Online (Sandbox Code Playgroud)
类型检查:
$> flow
hello.js:3:10,21: number
This type is incompatible with
hello.js:2:37,42: string
Run Code Online (Sandbox Code Playgroud)
以下是如何运行它.
VNO*_*VNO 12
不,相反,你需要根据自己的需要做这样的事情:
function myFunction(myDate, myString) {
if(arguments.length > 1 && typeof(Date.parse(myDate)) == "number" && typeof(myString) == "string") {
//Code here
}
}
Run Code Online (Sandbox Code Playgroud)
col*_*lxi 10
您可以使用函数中的包装器实现一个自动处理类型检查的系统.
使用这种方法,您可以构建一个完整的
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 2Run Code Online (Sandbox Code Playgroud)
它不是内置于语言中,但您可以很容易地自己完成.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
Run Code Online (Sandbox Code Playgroud)
可以使用ArgueJS轻松实现:
function myFunction ()
{
arguments = __({myDate: Date, myString: String});
// do stuff
};
Run Code Online (Sandbox Code Playgroud)