Search code examples
javascriptdocumentation-generationjsdoccode-documentationjsdoc3

JSDoc: Return object structure


How can I tell JSDoc about the structure of an object that is returned. I have found the @return {{field1: type, field2: type, ...}} description syntax and tried it:

/**
 * Returns a coordinate from a given mouse or touch event
 * @param  {TouchEvent|MouseEvent|jQuery.Event} e    
 *         A valid mouse or touch event or a jQuery event wrapping such an
 *         event. 
 * @param  {string} [type="page"]
 *         A string representing the type of location that should be
 *         returned. Can be either "page", "client" or "screen".
 * @return {{x: Number, y: Number}} 
 *         The location of the event
 */
var getEventLocation = function(e, type) {
    ...

    return {x: xLocation, y: yLocation};
}

While this parses successfully, the resulting documentation simply states:

Returns: 
    The location of an event
    Type: Object

I am developing an API and need people to know about the object that they will get returned. Is this possible in JSDoc? I am using JSDoc3.3.0-beta1.


Solution

  • Define your structure separately using a @typedef:

    /**
     * @typedef {Object} Point
     * @property {number} x - The X Coordinate
     * @property {number} y - The Y Coordinate
     */
    

    And use it as the return type:

    /**
     * Returns a coordinate from a given mouse or touch event
     * @param  {TouchEvent|MouseEvent|jQuery.Event} e    
     *         A valid mouse or touch event or a jQuery event wrapping such an
     *         event. 
     * @param  {string} [type="page"]
     *         A string representing the type of location that should be
     *         returned. Can be either "page", "client" or "screen".
     * @return {Point} 
     *         The location of the event
     */
    var getEventLocation = function(e, type) {
        ...
    
        return {x: xLocation, y: yLocation};
    }