jsDoc - how to specify array length
Asked Answered
F

3

12

In jsDoc I can specify my array parameters and members like this:

/**
 * @constructor
 * @param {Array.<string>} myArray
 */
function someFunction( myArray ){

    this.firstArray = myArray;

    /** @member {Array.<float>} */
    this.secondArray = [];

}

Is there also a way to specify the length, or minLength and maxLength of these arrays?

Fradin answered 1/4, 2014 at 12:42 Comment(0)
S
6

I think you're asking whether you can include the minimum/maximum length in the type expressions (for example, Array.<string>).

In short, the answer is no. You'll need to document the minimum/maximum length in the description of each array.

Slay answered 25/6, 2014 at 0:56 Comment(1)
I need to exactly describe the array length. Is there a way to do this?Orbadiah
H
8

While specifying the size [limits] of an Array is not possible, for fixed-length Arrays, like 'Tuples', a type expression can be used:

/**
 * @returns {[number, number, number]}
 */
function getLuckyThree() { … }
Heidelberg answered 13/1, 2022 at 20:59 Comment(1)
Thanks for adding that practical solution in an answer.Fradin
S
6

I think you're asking whether you can include the minimum/maximum length in the type expressions (for example, Array.<string>).

In short, the answer is no. You'll need to document the minimum/maximum length in the description of each array.

Slay answered 25/6, 2014 at 0:56 Comment(1)
I need to exactly describe the array length. Is there a way to do this?Orbadiah
H
3

I have looked through UseJSDoc.org and Google’s Closure Compiler, and neither documentation describes how to specify array length.

My guess is the compiler only checks for type, not for length, so even if there were syntax to explicitly describe array length, an array of the incorrect length would probably still pass the compiler (no error would be thrown).

The best way to do this is in the human-language description of the parameter and return type:

/**
 * Duplicates a 4-length array into itself.
 * e.g. `[2, 3, 5, 8] => [2, 2, 3, 3, 5, 5, 8, 8]`
 * @param   {Array<number>} arr the array to duplicate (exactly 4 entries)
 * @returns {Array<number>} the result (an array of length 8)
 */
function dupe(arr) {
  ...
}

FYI, you can use Array.<number>, or Array<number>, or even number[] inside the @type declaration.

If this feature is important to you (I’d certainly use it!), you can submit an issue.

Holbrooke answered 1/10, 2017 at 5:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.