JSDoc document argument that can only take a value from an enum array

564 Views Asked by At

I have checked this site for any answers that might solve my problem, yet none of them covers my case.

I have a function that changes color and takes a color argument. That function is supposed to only work on values included in the COLORS enum.

/**
 * @enum ???
 * or
 * @typedef ???
 */
const COLORS = ['green', 'yellow', 'red', 'none', null];

/**
 * @param {???} color color value from COLORS array
 */
function changeColor(color) {
  if (!COLORS.includes(color)) return;
  // ...
}

How would I properly document a) the enum COLORS, and b) the function argument color in JSDoc?

Edit: It seems my understanding of enum is wrong. By the looks of it an array of literals cannot be considered an enum. So if I want to stick with my current implementation, how else would I make clear that color can only be a value from COLORS?

1

There are 1 best solutions below

6
On

Based on JSDoc documentation for @constant, typedef, for the constant you could do something like the example below:

/** @constant
    @typedef {Array} COLORS
    @type {Array<?string>}
    @default
*/

const COLORS = ['green', 'yellow', 'red', 'none', null];

PS: Notice that ? is used to declare that Array value could be string or null. For more check the Nullable type in @type documentation.

For the Function:

/**
 * @param {?string} color - The color used, one of {@link COLORS}.
 */
function changeColor(color) {
  if (!COLORS.includes(color)) return;
  // ...
}