Skip to content

IntelliSense/JSDoc @param = @return, a.k.a. how do I document wrapper functions?

I have a function which takes in another function as an argument, does something to that function-argument, and then returns that same function-argument (or at least returns a function with the exact same signature to it)

/**
 * The param and return should be the same (as far as JSDoc is concerned)!
 * @param {Function} fnToWrap
 * @returns {fnToWrap}
 */
function wrapperFunction(fnToWrap) {
    // Does something...
    return fnToWrap;
}

However, as you can see from my comments in the following…

/**
 * IntelliSense detects this...
 * @param paramA 
 * @returns 
 */
var arbitraryFn = function(paramA) {
    return paramA * 2;
}


// But NOT this!!!
var wrappedArbitraryFn = wrapperFunction(arbitraryFn);

… IntelliSense will autocomplete when calling arbitraryFn() but not wrappedArbitraryFn().

Is there any way to get IntelliSense to dynamically autocomplete my wrapped functions with the same signature as their unwrapped counterparts, i.e. without having to explicitly re-document every newly-wrapped function?

Answer

I’m revisiting this again as I now have a (near-)perfect solution for my use-case. The reality is IntelliSense is far more TypeScript than it is standard JSDoc. As it turns out, you can leverage the @template tag to solve the above, and as far as I’ve seen, anything I can accomplish in TypeScript I can also accomplish in JavaScript IntelliSense:

The New Wrapper Function

/**
 * The param and return should be the same (as far as JSDoc is concerned)!
 * @template {Function} T
 * @param {T} fnToWrap
 * @returns {T}
 */
 function wrapperFunction(fnToWrap) {
    // Does something...
    return fnToWrap;
}

Wrapping a Previously-Declared Function

/**
 * IntelliSense detects this...
 * @param {Number} paramA 
 */
function previouslyDeclared(paramA) {
    return paramA * 2;
}

// And it also detects this!
var afterWrapping = wrapperFunction(previouslyDeclared);

Wrapping an inline Function

// And it also detects this!
var wrappedArbitraryFn = wrapperFunction(
    /**
     * IntelliSense detects this
     * @param {String} a 
     * @param {Number} b 
     * @param {Function} c 
     * @returns 
     */
    (a, b, c) => {
        return 22;
    }
);

Only downside for me is the inline is a bit ugly, imo, but it works. However, do note that this may not be a valid solution for true/vanilla JSDoc. This solution is great if, like me, you don’t really use/care about JSDoc and you’re really just here for the IntelliSense piece.