I am using jsdoc to document function parameters. One function is recursive, and accepts an array of objects that can be nested to arbitrary depths. Here's a simplified example:
const person = {
firstName: "Bob",
lastName: "Smith",
children: [{ firstName: "Bill", lastName: "Smith", children: [......] }] // an array of person shaped objects with values for firstName, lastName, and children
}
I tried writing something like this, but I'm not sure how to handle the recursion. Is there a simple way to do this, or would I have to define a class for this object?
/**
* @param person {{ firstName: string, lastName: string, children: person[] }}
* ^ this doesn't work
*/
I'm just using person
as an example -- in my actual app it's an object representing bulleted text with nesting.
You can use a @typedef
tag to define types. It also supports recursive types.
Your JSDoc could look like this:
/**
* @typedef Person
* @type {object}
* @property {string} firstname
* @property {string} lastname
* @property {Person[]} children
*/
/**
* @param {Person} person
*/
Or shorter (but arguably less readable):
/**
* @typedef {{firstname: string, lastname: string, children: Person[]}} Person
*/
/**
* @param {Person} person
*/
Note regarding "opting out of jsdoc @typedef
exports": You may want to watch issue #46011 of the microsoft/TypeScript
repository.