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

1

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

Encyclical answered 22/8, 2014 at 5:31 Comment(0)
C
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.

Crenation answered 22/8, 2014 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.