我想知道lodash如何根据用户输入的参数类型或数量,对他们所拥有的函数的参数进行分组建议,如下所示:
在上图中,可以看出在lodash中有关于each
函数的8组建议。以下是我案例中的示例代码:
功能示例:
function filter(allowSize, max) {
//do Something
}
如果filter
函数只有1个参数,请使用下面的jsdoc:
/**
* @param {object} allowSize
* @param {number} allowSize.min
* @param {number} allowSize.max
*/
我想从建议中删除
max
参数,但我不知道该怎么做
如果filter
函数有2个参数,请使用下面的jsdoc:
/**
* @param {number} allowSize
* @param {number} max
*/
我想在建议中将
allowSize
参数重命名为min
,但我不知道该怎么做
我如何使用jsdoc执行上述操作?
你可以使用函数重载方法,但javascript不支持这种方法。那你怎么做lodash?
答案是使用typescript编写代码的lodash.Typescript允许你使用重载方法编写函数.Typescript将生成一个扩展名为.d.ts
的文件,其中包含与编写的代码相关的信息。
例:
function filter(allowSize: object): any;
function filter(min: number, max: number): any;
function filter(arg1: object | number, arg2?: number): any {
if (typeof arg1 === "object") {
// do something when the function only have 1 parameter
} else if (typeof arg1 === "number" && typeof arg2 === "number") {
// do something when the function has 2 parameters
} else {
// default
}
}
之后,使用命令tsc -d typescript_file.ts
编译TS文件
-d
参数对于告诉编译器创建声明文件很有用。