如何使用有限的可能值记录jsdoc中的字符串类型

时间:2013-09-30 12:10:15

标签: google-closure-compiler google-closure jsdoc code-documentation

我有一个接受一个字符串参数的函数。此参数只能包含一些已定义的可能值。记录相同内容的最佳方法是什么?应该将shapeType定义为enum或TypeDef还是其他什么?

Shape.prototype.create = function (shapeType) {
    // shapeType can be "rect", "circle" or "ellipse"...
    this.type = shapeType;
};

Shape.prototype.getType = function (shapeType) {
    // shapeType can be "rect", "circle" or "ellipse"...
    return this.type;
};

问题的第二部分是shapeType的可能值在定义shapeType的文件中未知,无论您的建议如何。多个开发人员提供了多个文件,这些文件可能会添加shapeType的可能值。

PS:使用jsdoc3

5 个答案:

答案 0 :(得分:60)

从jsdoc3中的late 2014开始,你可以写:

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

当然,这不会像专用枚举一样可重复使用,但在许多情况下,如果虚拟枚举仅由一个函数使用,则它是一种过度杀伤。

另请参阅:https://github.com/jsdoc3/jsdoc/issues/629#issue-31314808

答案 1 :(得分:15)

如何声明虚拟枚举:

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

为此,您至少需要向JSDOC声明枚举。但代码很干净,你可以在WebStorm中自动完成。

多文件问题虽然无法通过这种方式解决。

答案 2 :(得分:6)

那又怎么样:

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

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

enter image description here

答案 3 :(得分:3)

我认为在JSDoc中有一种正式的写入允许值的方式。

您当然可以像提及用户b12toaster之类的@param {String('up'|'down'|'left'|'right')}之类的内容。

enter image description here

但是,通过参考APIDocjs,这是我用来编写约束值的东西,又名 allowedValues

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

哦,是的,我正在使用ES6。

答案 4 :(得分:0)

Closure Compiler支持它:您可以使用“@enum”来定义受限类型。您实际上不必在枚举定义中定义值。例如,我可能会定义一个“整数”类型,如:

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

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

Int通常可分配给“number”(它是一个数字)但是“number”在没有强制(强制转换)的情况下不能分配给“Int”。