2

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).

Ahmed Fasih
  • 5,979
  • 3
  • 43
  • 86

1 Answers1

4

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.

Louis
  • 128,628
  • 25
  • 249
  • 295