Home > Enterprise >  How do I document "provider-pattern" functions with JSDoc in TypeScript?
How do I document "provider-pattern" functions with JSDoc in TypeScript?

Time:08-04

Taking a minimal example, here is what I'm calling a "provider-pattern" function (please correct me if there's another name here).

export const callEndpointProvider = (endpointToCall: string) => 
  async (accessToken: string): Promise<null> => { 
    return null 
  }

I'd like to document this function with JSDoc in such a way that the returned function is documented, not necessarily the provider itself.

I've looked around on the internet and SO and can't seem to find anything to point me in the right direction, so for now I've sufficed with documenting the provider itself as though it was the provided function.

The issue with this approach being, I don't get the nice IDE tooltips on my provided function after initializing the provider.

JSDoc example (currently what I have):

/**
* A function that returns null
* @async
* @return {null} - A null value
*/

I'm also open to alternatives to JSDoc if there's something that fits this usecase better, as we use this pattern a lot.

CodePudding user response:

You can do that by putting the JSDoc inside the function, annotating the returned function:

export const callEndpointProvider = (endpointToCall: string) => {
    /**
     * A function that returns null.
     *
     * @param   accessToken The access token to use.
     */
    return async (accessToken: string): Promise<null> => {
        return null;
    };
};

(Since you're using TypeScript, the types don't have to be in the JSDoc.)

Here's an example of using the returned function and the information associated with it (in this case, by VS Code):

VS Code editor showing using the function returned by the function above, with the info panel with function documentation.

That's in addition to documenting the function itself, of course:

/**
 * A function returning a function to call an endpoint.
 *
 * @param   endpointToCall  The endpoint the returned function will call.
 * @returns The function.
 */
export const callEndpointProvider = (endpointToCall: string) => {
    /**
     * A function that returns null.
     *
     * @param   accessToken The access token to use.
     */
    return async (accessToken: string): Promise<null> => {
        return null;
    };
};
  • Related