是否有一种方法可以让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不是静态类型语言。有时可能需要手动检查函数体中的参数类型。

解释

我不确定我的答案是否直接回答了最初的问题,但我想很多人来这里只是为了找到一种方法让他们的ide理解类型,我将分享我的发现。

如果你想让VSCode理解你的类型,请按照下面的步骤进行。请注意,js运行时和NodeJS根本不关心这些类型。

解决方案

1-用.d创建一个文件。Ts结尾:例如:index.d.ts。您可以在另一个文件夹中创建此文件。例如:types/index.d.ts 假设我们想要一个叫做view的函数。将这些行添加到index.d.ts中:

/**
 * Use express res.render function to render view file inside layout file.
 *
 * @param {string} view The path of the view file, relative to view root dir.
 * @param {object} options The options to send to view file for ejs to use when rendering.
 * @returns {Express.Response.render} .
 */
view(view: string, options?: object): Express.Response.render;

3-创建jsconfig。Json文件在你的项目的根。(看起来仅仅创建这个文件就足以让VSCode搜索你的类型了)。

再多一点

现在假设我们想把这个类型添加到另一个库类型中。(就我自己的情况而言)。我们可以使用一些ts的关键字。只要VSCode理解ts,我们就没有问题。 例如,如果你想把这个视图函数添加到response from expressjs中,修改index.d.ts文件如下:

export declare global {
  namespace Express {
    interface Response {
      /**
       * Use express res.render function to render view file inside layout file.
       *
       * @param {string} view The path of the view file, relative to view root dir.
       * @param {object} options The options to send to view file for ejs to use when rendering.
       * @returns {Express.Response.render} .
       */
      view(view: string, options?: object): Express.Response.render;
    }
  }
}

结果

编辑:七年后,这个答案仍然偶尔会得到点赞。如果您正在寻找运行时检查,这很好,但我现在建议使用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

使用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');
}

您可以在函数中使用包装器来实现自动处理类型检查的系统。

使用这种方法,您可以构建一个完整的声明式类型检查系统,该系统将为您管理类型检查。 如果您有兴趣更深入地了解这个概念,请查看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