Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to document array elements? #1073

Open
brunano21 opened this issue Sep 24, 2015 · 17 comments
Open

How to document array elements? #1073

brunano21 opened this issue Sep 24, 2015 · 17 comments
Labels
Milestone

Comments

@brunano21
Copy link

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?

@glumb
Copy link

glumb commented Nov 28, 2015

Same question for me.

@IanVS
Copy link

IanVS commented Dec 25, 2015

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?

@ElfenLiedGH
Copy link

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];
}

@dandv
Copy link
Contributor

dandv commented Jun 12, 2017

/**
 * 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?

@hegemonic hegemonic added this to the Future milestone Jul 2, 2017
@hegemonic
Copy link
Contributor

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) {}

@kenbellows
Copy link

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) {
    //...
}

not-an-aardvark pushed a commit to eslint/eslint that referenced this issue Jan 20, 2018
JSDoc syntax errors were causing "npm run docs" to fail.

- JSDoc doesn't yet support specifying array content, i.e. "[number,
  number]" is a syntax error, so I'm using "number[]" instead. (source:
  jsdoc/jsdoc#1073)

- JSDoc doesn't support multiline objects, e.g. returning report information
  was a syntax error, so I extracted it into a typedef, as well as the
  disable directive.
@brettz9
Copy link

brettz9 commented Jun 26, 2018

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

@pke
Copy link

pke commented Jan 5, 2020

Any updates on this from the maintainers?

@mqliutie
Copy link

mqliutie commented Jun 3, 2020

What if the array is defined like

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

or

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

@brunoenribeiro
Copy link

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

@zerkms
Copy link

zerkms commented Nov 24, 2020

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

@brunoenribeiro
Copy link

brunoenribeiro commented Dec 1, 2020

@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

@brettz9
Copy link

brettz9 commented Dec 1, 2020

@brunoenribeiro , @zerkms : VisualStudio is using TypeScript's own extension of JSDoc. JSDoc itself does not appear to support the "tuples" you are describing; see #1703 nor do its docs embrace such a type (and Closure, whose types JSdoc mentions supporting, doesn't either: google/closure-compiler#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.

@de1mat
Copy link

de1mat commented Oct 5, 2021

What if the array is defined like

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

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

@VictorioMolina
Copy link

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.

@haseebanwar
Copy link

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

@kungfooman
Copy link

kungfooman commented Aug 5, 2022

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:

hegemonic/catharsis#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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests