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

Sha*_*rya 69 code-documentation google-closure google-closure-compiler jsdoc

我有一个接受一个字符串参数的函数.此参数只能包含一些已定义的可能值.记录相同内容的最佳方法是什么?应该将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;
};
Run Code Online (Sandbox Code Playgroud)

问题的第二部分shapeType是在文件中不知道可能的值,它定义shapeType为您建议的任何内容.有几个开发人员提供了多个文件,可能会添加可能的值shapeType.

PS:我正在使用 jsdoc3

B12*_*ter 74

截至2014年底 jsdoc3你有可能写:

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

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

另见:https://github.com/jsdoc3/jsdoc/issues/629#issue-31314808

  • 如果您知道参数类型永远不会改变,则这是一个更好的解决方案。 (2认同)

Seb*_*ian 16

如何声明一个虚拟枚举:

/**
 * 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)
Run Code Online (Sandbox Code Playgroud)

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

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


Ala*_*ong 10

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

您当然可以编写类似于提到的@param {String('up'|'down'|'left'|'right')}用户b12toaster 之类的内容

在此处输入图片说明

但是,通过参考APIDocjs,这是我用于编写受约束的值,又名allowedValues 的内容

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

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

  • `@param` 不允许这种类型的语法。最标准的方法是`@param {"up"|"down"|"left"|"right"} [position=left] - 指针位置`。 (3认同)

小智 9

关于什么:

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

/**
 * @param format {MetricFormat}
 */
export function fetchMetric(format) {
    return fetch(`/matric}`, format);
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明