是否有一种方法可以让javascript函数知道某个参数是某个类型的?
能够做这样的事情将是完美的:
function myFunction(Date myDate, String myString)
{
//do stuff
}
谢谢你!
更新:作为答案是一个响亮的“不”,如果我想myDate被视为一个日期(为了在它上调用日期函数),我必须将其转换为函数内的日期或设置一个日期类型的新变量?
是否有一种方法可以让javascript函数知道某个参数是某个类型的?
能够做这样的事情将是完美的:
function myFunction(Date myDate, String myString)
{
//do stuff
}
谢谢你!
更新:作为答案是一个响亮的“不”,如果我想myDate被视为一个日期(为了在它上调用日期函数),我必须将其转换为函数内的日期或设置一个日期类型的新变量?
当前回答
不,相反,你需要根据你的需要做这样的事情:
function myFunction(myDate, myString) {
if(arguments.length > 1 && typeof(Date.parse(myDate)) == "number" && typeof(myString) == "string") {
//Code here
}
}
其他回答
不是在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
不,相反,你需要根据你的需要做这样的事情:
function myFunction(myDate, myString) {
if(arguments.length > 1 && typeof(Date.parse(myDate)) == "number" && typeof(myString) == "string") {
//Code here
}
}
我假设您允许IDE帮助您;那么下面的答案可能会帮助你。
IDE: jetbrains/Golang如果你的IDE不是这个也没关系。我相信所有支持JSDoc的IDE都能满足您的大部分需求。
它可以很好地显示JSDoc。
Demo
我的- pkg base64编码- js。
/**
* Convert string to the base64 format.
*
* @param str {string} Input string
* @returns {string} some message about return...
* @example
* - btoa(toBinary("☸☹☺☻☼☾☿"))
* - Str2base64("☸☹☺☻☼☾☿")
* @see https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa#unicode_strings
*/
export function Str2base64(str) {
return btoa(toBinary(str))
}
. js
import * as base64 from "../pkg/encoding/base64"
const filenameB64 = base64.Str2base64("test")
有用的JSDoc文档
JSDoc块标签 显示@returns, @param, @type…
其他链接
jetbrains JSDoc /评论
编辑:七年后,这个答案仍然偶尔会得到点赞。如果您正在寻找运行时检查,这很好,但我现在建议使用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
不,JavaScript不是静态类型语言。有时可能需要手动检查函数体中的参数类型。