繁体   English   中英

我如何像 lodash 一样使用 JSDoc 对参数进行分组?

[英]how do I group parameters with JSDoc like lodash?

我想知道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怎么做呢?

答案是lodash使用 typescript 编写代码。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参数对于告诉编译器创建声明文件很有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM