6

I've been trying to document an overload function in JS using JSDoc:

There's 2 use cases:

assignSlave(ticket, userid);
assignSlave(ticket, firstname, lastname);

I'd like to have it look like this in VSCode:

  • Case 1

    Case 1

  • Case 2

    Case 2

And so on...

I tried the solution given in Document overloaded function in JSDoc but it didn't work for me:

/**
 * Test
 *
 * @function assignSlave
 * @param {String} ticket
 * @param {String} userid
 *//**
 * Test2
 *
 * @function assignSlave
 * @param {String} ticket
 * @param {String} firstname
 * @param {String} lastname
 */
function assignSlave(a, b, c){}
assignSlave()

I get this:

this

Is there a way to achieve what I'm trying to do?

I read this article but am not sure how it works in my case.

2

2 Answers 2

10

In TypeScript 5, you can use the new @overload tag:

/**
 * @overload
 * @param {string} ticket
 * @param {string} userId
 *//**
 * @overload
 * @param {string} ticket
 * @param {string} firstname
 * @param {string} lastname
 *//**
 * @param {string} a
 * @param {string} b
 * @param {string} c
 */
function assignSlave(a, b, c) {}

For reference: https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#overload-support-in-jsdoc

Sign up to request clarification or add additional context in comments.

Comments

3

Do it like the following snippet. Change from function to an arrow function and set its type accordingly. The last thing is to assign a default value to trailing arguments so the overload types are compatible with each other.

/**
 * @type  {{
 *   (ticket: string, userid: string): void;
 *   (ticket: string, firstname: string, lastname: string): void;
 * }}
 */
 const assignSlave = (a, b, c = '') => {}
 assignSlave('ticket', 'userid')
 assignSlave('ticket', 'firstname', 'lastname')

This way the function is recognized with 2 overloads:

Overload 1

Overload 1

Overload 2

Overload 2

4 Comments

Thank you so much !! It works exactly like I wanted to !
I don't know how to do, I don't see the chcek button ;_; Never mind, I'm dumb
While this works, you should note that you unfortunately lose typing on the anonymous inner function. In the above example, the types of a, b, and c are all any. Similarly that function can return whatever it likes and is not constricted to void.
@Mark You don't actually, you just have to remember to also add @param fields just like you would normally. The type just takes care of when you use it elsewhere.

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.