jsdoc icon indicating copy to clipboard operation
jsdoc copied to clipboard

How to document array elements?

Open brunano21 opened this issue 8 years ago • 17 comments

Hi, I have a function that takes an array of strings. Something like:

function myFunc(args) {
    var a = args[0];
    var b = args[1];
}

But I want to specify what each element within the array represents. How can I achieve that? I tried with something like:

/**
 * @param {String[]} args
 * @param {String}  args.0 - attribute name.
 * @param {String}  args.1 - value to set.
 */

But obviously this is wrong since they are interpreted as properties. Of course, I also tried with args[0] but I get an error at jsdoc generation phase. Finally, Google did not help this time. :/ Any suggestion?

brunano21 avatar Sep 24 '15 13:09 brunano21

Same question for me.

glumb avatar Nov 28 '15 21:11 glumb

I'm also wondering this. In my case, I have a typedef of an array, for which the first element has a particular significance and should always be a number. Any suggestions how to document this?

IanVS avatar Dec 25 '15 03:12 IanVS

i'm using it

        /**
            @typedef AR_INNERJOIN
            @type {Set}
            @property {string} полеСвязи имя поля свзя, по которому осуществлять соединение, либо псевдоним при  отсутсвии поля связи в словаре
            @property {string} имяТаблицы имя таблицы, которую присоединяем ( при отсутсвии поля связи в словаре )
            @property {string} условие условие соединения, Пример t1.ROW_ID = t3.Счет
            @property {string} типСоединения по умолчанию LEFT JOIN, при необходимости можно указать просто JOIN, FULL JOIN  и т.д
            @property {string} неТребуетПолей если заполнено, то поля этого присоединения в SELECT не попадут
        */

        /**
         * набор внутренних присоединений к выборке
         * @type {AR_INNERJOIN}
         */
        this.внутренниеПрисоединения = new Set(); 

1 click AR_INNERJOIN 1

@typedef MyArray
@type {array}
@property {string} 0 - attribute name.
@property {string} 1 - value to set.

@param {MyArray}
function myFunc(args) {
    var a = args[0];
    var b = args[1];
}

ElfenLiedGH avatar Dec 25 '15 07:12 ElfenLiedGH

/**
 * The `@returns` below was autogenerated by WebStorm:
 * @returns {Promise.<{f: [number,number], b: [string,string]}>}
 */
foo() {
  return Promise.resolve({
    f: [1, 2],
    b: ['bar', 'baz']
  })
}

Is this correct (but under-documented) JSDoc?

dandv avatar Jun 12 '17 06:06 dandv

There's currently no way to document the expected type of individual array elements. The best you can do is the workarounds proposed by @brunano21 and @ElfenLiedGH. Or, of course, you can just use text:

/**
 * Foo function.
 *
 * @param {Array} bar - The bar array. The first element must be a number, and the
 * second element must be a string.
 */
function foo(bar) {}

I'm open to a pull request that supports something like the following example (inspired by WebStorm), but keep in mind that most of the work will involve modifying the Catharsis type-expression parser:

/**
 * Foo function.
 *
 * @param {[number, string]} bar - The bar array.
 */
function foo(bar) {}

hegemonic avatar Jul 02 '17 23:07 hegemonic

Just wanted to probe this issue again. Has any progress been made on this issue?

For my two cents, the format generated (an presumably supported, though I haven't checked) by WebStorm makes a lot of sense to me, especially in return statements:

/**
 * Calculate the x and y coordinates of a point given a vector
 * @param {Vector} v
 * @returns [Number, Number]    x and y coords in pixels of the point indicated by the vector
 */
function getPointFromVector(v) {
    //...
}

kenbellows avatar Jan 16 '18 16:01 kenbellows

While it is not great DRY, one advantage of the @property {type} index - Description approach would be that a named label might be made allowable after the index to represent the item, e.g.:

/**
* @property {string} 0 type The type that...
* @property {string} 1 value The value which ...
*/

And if the list is long, the numeric indexes also do help one see at a glance what the number is without having to count commas....

brettz9 avatar Jun 26 '18 03:06 brettz9

Any updates on this from the maintainers?

pke avatar Jan 05 '20 02:01 pke

What if the array is defined like

const myList = [1,' hellow', true, { a: 1 }]

or

const [hello, world] = 'hello world'.split(' ');

mqliutie avatar Jun 03 '20 06:06 mqliutie

Now it's possible to document arrays like this (at least on VS Code): Captura de tela de 2020-11-24 16-18-31

It's also possible to name elements: Captura de tela de 2020-11-24 16-19-20

brunoenribeiro avatar Nov 24 '20 19:11 brunoenribeiro

@brunoenribeiro what exact values are expected to be passed in both of your examples? It's not immediately clear what a named element in an array is.

zerkms avatar Nov 24 '20 21:11 zerkms

@brunoenribeiro what exact values are expected to be passed in both of your examples? It's not immediately clear what a named element in an array is.

Hey there! Sorry for the delay.

In both cases, you should pass an array with 2 elements. For instance: [0, 'zerkms'].

There'll be no difference to the code itself. The only difference is how much information will be provided in the documentation.

Other example: suppose you have a function vector3Adapter() that receive an array with 3 numbers, one for each coordinate.

In your docs, you could declare only that there'll be 3 numbers... Captura de tela de 2020-12-01 18-30-37

... but you could name each element and make it much clearer: Captura de tela de 2020-12-01 18-23-11

But you still can destructure the array using any names you want: Captura de tela de 2020-12-01 18-26-07

brunoenribeiro avatar Dec 01 '20 21:12 brunoenribeiro

@brunoenribeiro , @zerkms : VisualStudio is using TypeScript's own extension of JSDoc. JSDoc itself does not appear to support the "tuples" you are describing; see https://github.com/jsdoc/jsdoc/issues/1703 nor do its docs embrace such a type (and Closure, whose types JSdoc mentions supporting, doesn't either: https://github.com/google/closure-compiler/issues/379 ).

(Side: note: these "tuples" are not the same as those in the stage 2 JS proposal: https://github.com/tc39/proposal-record-tuple ).

Of course, it's good to know about this for those who are using the TypeScript extension, and it'd be nice for it to be supported.

brettz9 avatar Dec 01 '20 23:12 brettz9

What if the array is defined like

const [hello, world] = 'hello world'.split(' ');

I would like to know the answer to this as well...

de1mat avatar Oct 05 '21 21:10 de1mat

This way


/**
 * Foo function.
 *
 * @param {[number, string]} bar - The bar array.
 */
function foo(bar) {}

is throwing an error in the last versions of the library.

VictorioMolina avatar Mar 10 '22 10:03 VictorioMolina

If you want to define valid string values that an array can accept, you can do it like this

/**
 * @param {Array<('cjs' | 'es' | 'iife')>} formats
 * @returns {void}
 */
function config(formats) {
}

image

haseebanwar avatar May 05 '22 13:05 haseebanwar

I opened a PR to finally fix this, if you care enough, please test and feedback. This issue is open way too long by now:

https://github.com/hegemonic/catharsis/pull/70

It supports tuples as they are in TypeScript (unnamed + named tuples).

Even tho catharsis is able to parse tuples after this PR is merged and jsdoc would use the latest version, the AST still needs to be handled in jsdoc. I posted example AST's in the PR, if you want to help with this.

kungfooman avatar Aug 05 '22 12:08 kungfooman