Search code examples
javascriptnode.jsexpressjsdoc

How to reuse same params definitions in functions with JSDoc


I've HTTP handlers in my express application. I'd like to annotate with JSDoc these handlers in a reusable way.

Right now, I've the following:

/**
 * 
 * @param {functions.Request} req 
 * @param {functions.Response} res 
 */
const createNewCompanyService = (req, res) => {

}

/**
 * 
 * @param {functions.Request} req 
 * @param {functions.Response} res 
 */
const updateNewCompanyService = (req, res) => {
    
}

How can I reuse the JSDoc declaration in different function expressions?

I'm looking for something like this:

/**
 * @typedef HttpHandlerFn
 * @type {function}
 * @param {functions.Request} req - The Request Object
 * @param {functions.Response} res - The Response Object
 */

Solution

  • You can do it this way:

    /**
     * @typedef {function(functions.Request, functions.Response)} HttpHandlerFn
     */
    
    /**
     * @type {HttpHandlerFn}
     */
    const createNewCompanyService = (req, res) => {
    
    }
    
    /**
     * @type {HttpHandlerFn}
     */
    const updateNewCompanyService = (req, res) => {
    
    }
    

    HttpHandlerFn is defined as a function that takes in a Request and Response object from the functions module. You can then use this HttpHandlerFn type to annotate your handler functions.