JSDoc3 documentation of a function's argument being an array of objects?

对着背影说爱祢 提交于 2019-12-22 11:33:31

问题


UseJSDoc.org's page on @type explains how to document arrays and objects, but not arrays of objects. My function accepts an array of objects with a specific list of properties and it's these properties that I'd like to document.

The function might look like function foo(people) and the people array might have been created by the caller of the function as

arr = [];
arr.push({name: "Alfred", profession: "Butler", hitpoints: 2});
arr.push({name: "Batman", profession: "Vigilante", hitpoints: 42});
// ...
foo(arr)

I'd like to use the {{name: string, profession: string, hitpoints: number}} Person syntax to document the objects but also include a notion that they've got to be in an array.

Note that the underlying object (what I call Person above, though the code will not refer to anything as that) isn't a proper class, isn't even named anywhere. Nor is a single "Person" defined anywhere for me to use the @property tag.

This difficulty in documenting this kind of code with JSDoc3 might suggest poor organization, and I'd happily consider advice on how to reorganize ephemeral objects like this, used mainly as hash tables (associative arrays).


回答1:


Here are two ways to do it:

/**
 * @param {Array.<{name: string, profession: string, hitpoints: number}>} people The people.
 */
function foo(people) {
}

/**
 * @typedef Person
 * @property {string} name
 * @property {string} profession
 * @property {number} hitpoints
 */

/**
 * @param {Array.<Person>} people The people.
 */
function foo2(people) {
}

Note that you can tell jsdoc about things that don't actually exist in your code. @typedef is a prime example. I've also used @class to document abstract data structures that @typedef cannot handle. I've noted in the documentation that these are pseudo-classes that do not have any corresponding "class" in the JavaScript code.



来源:https://stackoverflow.com/questions/25440142/jsdoc3-documentation-of-a-functions-argument-being-an-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!