简体   繁体   中英

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). When I try to use this method in other places WebStorm and VSCode complain, that the 3rd parameter is needed instead of being optional

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?

I couldn't find a way to get your issue to go away by using the inline function definition for @type . 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. I first declare a @callback function type, and then set the variable's type to it. 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. So if maintaining JSDoc's syntax isn't a priority, the following way should work and is more concise:

/**
 * @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. So, if you still have an issue, explicitly making the rest argument optional is a possibility. It seemed to work when I tried it, though it isn't valid TypeScript syntax.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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