简体   繁体   中英

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

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.

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 编辑器显示使用上述函数返回的函数,以及带有函数文档的信息面板。

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;
    };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM