Search code examples
typescriptjsdoc

Forwarding JSDoc for object members whose source is a variable


I have a function documented with JSDoc which then becomes part of an object literal.

How can I forward the documentation for the function to the object literal, and thus make it available to an external scope (such as outside an outer function, or a different module)?

I could write the JSDoc on the object literal itself, but I don't want to move the JSDoc from the function.

const { printRandom } = (() => {
    /**
     * Prints a random number
     */
    const printRandom = () => console.log(Math.random())

    return {
        printRandom
    }
})()

In other words, in VSCode when hovering over the printRandom variable in the outer scope, I would like to see the text Prints a random number instead of just the function signature.

enter image description here

Some additional notes

  • While VS Code doesn't display the JS Doc at the variable exported from the function/module, it does display at the function call site:

    enter image description here

    But it doesn't do so at the usage site of arbitrary variables/properties, so the question is still useful.


Solution

  • Instead of keeping the documentation separate from the object literal, it is possible to move the documentation to within the object literal.

    const { printRandom, foo } = (() => {
        return {
            /**
             * Prints a random number
             */
            printRandom: () => console.log(Math.random()),
    
            /**
             * Arbitrary number
             */
            foo: 4
        }
    })()
    

    This works at the object destructuring (into printRandom and foo) and also at the usage sites of both functions and variables (at least, for VS Code).

    enter image description here