How to document a string type in jsdoc with limited possible values

流过昼夜 提交于 2019-11-27 18:55:29

How about declaring a dummy enum:

/**
 * Enum string values.
 * @enum {string}
 */
Enumeration = {
    ONE: "The number one",
    TWO: "A second number"
};

/**
 * Sample.
 * @param {Enumeration} a one of the enumeration values.
 */
Bar.prototype.sample = function(a) {};


b = new Bar();

bar.sample(Enumeration.ONE)

You need to at least declare the enum to JSDOC, for this, though. But the code is clean and you get auto-completion in WebStorm.

The multiple files problem though cannot be solved this way.

As of late 2014 in jsdoc3 you have the possibility to write:

/**
 * @param {('rect'|'circle'|'ellipse')} shapeType - The allowed type of the shape
 */
Shape.prototype.getType = function (shapeType) {
  return this.type;
};

Of course this will not be as reusable as a dedicated enum but in many cases a dummy enum is an overkill if it is only used by one function.

See also: https://github.com/jsdoc3/jsdoc/issues/629#issue-31314808

What about:

/**
 * @typedef {"keyvalue" | "bar" | "timeseries" | "pie" | "table"} MetricFormat
 */

/**
 * @param format {MetricFormat}
 */
export function fetchMetric(format) {
    return fetch(`/matric}`, format);
}

Alan Dong

I don't think there's a formal way of writing allowed values in JSDoc.

You certainly can write something like @param {String('up'|'down'|'left'|'right')} like user b12toaster mentioned.

But, by taking reference from APIDocjs, here's what I use for writing constrained values, aka allowedValues.

/**
 * Set the arrow position of the tooltip
 * @param {String='up','down','left','right'} position pointer position
 */
setPosition(position='left'){
  // YOUR OWN CODE
}

Oh yeah, I'm using ES6.

This is how the Closure Compiler supports it: you can use "@enum" to define a restricted type. You don't actually have to define the values in enum definition. For instance, I might define an "integer" type like:

/** @enum {number} */
var Int = {};

/** @return {Int} */
function toInt(val) {
  return /** @type {Int} */ (val|0);
}

Int is generally assignable to "number" (it is a number) but "number" is not assignable to "Int" without some coercion (a cast).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!