简体   繁体   English

如何在 JSDoc 中使用 Function 类型注释 object 类型,该类型具有可变数量的 arguments?

[英]How to annotate an object with Function type that has variable number of arguments in JSDoc?

I got the following code:我得到以下代码:

/**
 * @type {function(boolean, string, ...*):void}
 */
exports.warn = createMacro(macro)

warn is a function whose signature is (arg1, arg2, ...arg3). warn是一个 function,其签名为 (arg1, arg2, ...arg3)。 When I try to use this method in other places WebStorm and VSCode complain, that the 3rd parameter is needed instead of being optional当我尝试在其他地方使用此方法时,WebStorm 和 VSCode 抱怨说,需要第三个参数而不是可选的

IDE中带下划线的代码

When generating the .d.ts file based on this comment the signature is correct: arg0: boolean, arg1: string, ...args: any[] How can I modify the annotation so the IDE does not complain about the missing parameter?根据此注释生成.d.ts文件时,签名是正确的: arg0: boolean, arg1: string, ...args: any[]如何修改注释以便 IDE 不会抱怨缺少参数?

I couldn't find a way to get your issue to go away by using the inline function definition for @type .通过使用 @type 的内联 function 定义,我找不到解决go问题的方法。 However there were a couple of alternatives that have a few drawbacks that you may consider.但是,有几个替代方案有一些缺点,您可以考虑。

The first way uses JSDoc syntax and should be compatible with any tool that reads it.第一种方式使用 JSDoc 语法,并且应该与任何读取它的工具兼容。 I first declare a @callback function type, and then set the variable's type to it.我首先声明了一个@callback function 类型,然后将变量的类型设置为它。 By wrapping the last parameter name in brackets, that parameter becomes optional and that should clear up your error.通过将最后一个参数名称括在括号中,该参数将变为可选,并且应该可以清除您的错误。

/**
 * @callback WarnFunc
 * @param {boolean} arg1
 * @param {string} arg2
 * @param {...*} [restParam]
 * @returns void
 */
/** @type WarnFunc*/
exports.warn = createMacro(macro);

The problem with the above is that it is much more verbose than what you had before.上面的问题是它比你以前的要冗长得多。 TypeScript supports the type parameter being defined in TypeScript's syntax as well as JSDoc's. TypeScript 支持在 TypeScript 语法和 JSDoc 中定义的类型参数。 So if maintaining JSDoc's syntax isn't a priority, the following way should work and is more concise:因此,如果维护 JSDoc 的语法不是优先事项,那么以下方式应该可以工作并且更简洁:

/**
 * @type {(arg1: boolean, arg2: string, ...restArgs: string[]) => void}
 */
exports.warn = createMacro(macro);

I didn't get any errors when I did things this way but the restArgs parameter didn't show as optional, either.当我这样做时,我没有收到任何错误,但restArgs参数也没有显示为可选。 So, if you still have an issue, explicitly making the rest argument optional is a possibility.因此,如果您仍有问题,可以明确地将 rest 参数设为可选。 It seemed to work when I tried it, though it isn't valid TypeScript syntax.当我尝试它时它似乎工作,虽然它不是有效的 TypeScript 语法。

@type {(arg1: boolean, arg2: string, ...restArgs?: string[]) => void}

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

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