Search code examples
javascriptjsdoc

Can I reference a param type in JSDoc @return?


I would like to document a function whose return type depends on the supplied parameter:

/**
* @param {*} x A thing
* @return {????} The thing in an array
*/
function arrayOf(x) { return [x]; }

Is it possible to name or otherwise reference the actual type of the function param, so that I can use it to specify the return?


Solution

  • I commented on the other answer that what I'm looking for boils down to a generic parameter, which is implemented in JSDoc with @template. I don't know if it's part of core JSDoc -- I think it's a Closure extension -- but Typescript does recognize it if you're running your JS through TS, or just trying to get autocomplete working in your IDE.

    Adapted from that link:

    /**
     * @template T
     * @param {T} x - A generic parameter that flows through to the return type
     * @return {T[]}
     */
    function id(x) {
      return [x];
    }