How to describe “object” arguments in jsdoc?

前端 未结 6 1477
迷失自我
迷失自我 2020-11-28 00:39
// My function does X and Y.
// @params {object} parameters An object containing the parameters
// @params {function} callback The callback function
function(paramet         


        
6条回答
  •  清歌不尽
    2020-11-28 01:12

    By now there are 4 different ways to document objects as parameters/types. Each has its own uses. Only 3 of them can be used to document return values, though.

    For objects with a known set of properties (Variant A)

    /**
     * @param {{a: number, b: string, c}} myObj description
     */
    

    This syntax is ideal for objects that are used only as parameters for this function and don't require further description of each property. It can be used for @returns as well.

    For objects with a known set of properties (Variant B)

    Very useful is the parameters with properties syntax:

    /**
     * @param {Object} myObj description
     * @param {number} myObj.a description
     * @param {string} myObj.b description
     * @param {} myObj.c description
     */
    

    This syntax is ideal for objects that are used only as parameters for this function and that require further description of each property. This can not be used for @returns.

    For objects that will be used at more than one point in source

    In this case a @typedef comes in very handy. You can define the type at one point in your source and use it as a type for @param or @returns or other JSDoc tags that can make use of a type.

    /**
     * @typedef {Object} Person
     * @property {string} name how the person is called
     * @property {number} age how many years the person lived
     */
    

    You can then use this in a @param tag:

    /**
     * @param {Person} p - Description of p
     */
    

    Or in a @returns:

    /**
     * @returns {Person} Description
     */
    

    For objects whose values are all the same type

    /**
     * @param {Object.} dict
     */
    

    The first type (string) documents the type of the keys which in JavaScript is always a string or at least will always be coerced to a string. The second type (number) is the type of the value; this can be any type. This syntax can be used for @returns as well.

    Resources

    Useful information about documenting types can be found here:

    https://jsdoc.app/tags-type.html

    PS:

    to document an optional value you can use []:

    /**
     * @param {number} [opt_number] this number is optional
     */
    

    or:

    /**
     * @param {number|undefined} opt_number this number is optional
     */
    

提交回复
热议问题