3

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

code underlined in 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?

1 Answer 1

2

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}
Sign up to request clarification or add additional context in comments.

4 Comments

This does not work. The IDE thinks it needs 2-3 parameters (when it can accept 2 or more) also the .d.ts file has wrong signature: export var warn: (arg0: boolean, arg1: string, arg2: any[] | undefined) => void;.
Sorry about that @sydd. I updated my answer with a couple of alternatives.
Thanks, it works! I guess this is a TS language server bug?
Turns out, this was a TS bug, its fixed now: github.com/microsoft/TypeScript/pull/44864 . Slated to release with TS 4.4.1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.