javascriptjsdocjsdoc3

Return type is one of the value from array


I have function which takes an array in an object as parameter. It calculates and return one of the value from that array. Is there a way to document the return type from one of the values from array dynamically.

Say

function random(params) {
  // calculate
  int random = 2; // this will change
  return params.values[random];
}

random({
  prop1: 'lorem ipsum',
  prop2: 3.444,
  values: [ 'value1', 'value2', 'value3', 'value4' ]
})

So random jsdoc should be dynamic but should look something like

/**
 * Some radom generator.
 * @param {object} props - Function parameters.
 * @param {string} props.prop1 - Some prop1.
 * @param {number} props.prop1 - Some prop2.
 * @param {string[]} props.values - List of values to pick.
 * @returns {('value1'|'value2'|'value3'|'value4')}
 */

The last return should somehow be dynamic


Solution

  • The following would do the trick:

    /**
     * Some random generator.
     * @template {string} T
     * @param {object} params - Function parameters.
     * @param {string} params.prop1 - Some prop1.
     * @param {number} params.prop2 - Some prop2.
     * @param {T[]} params.values - List of values to pick.
     * @returns {T}
     */
    

    enter image description here