我有一个接受一个字符串参数的函数。此参数只能包含一些已定义的可能值。记录相同内容的最佳方法是什么?应该将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
如何声明一个虚拟枚举:
/**
* 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中自动完成。
多文件问题虽然无法通过这种方式解决。
从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
我不认为在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
}
哦是的,我正在使用ES6。
这就是Closure Compiler支持它的方式:您可以使用“@enum”来定义受限类型。您实际上不必在枚举定义中定义值。例如,我可能会定义一个“整数”类型,如:
/** @enum {number} */
var Int = {};
/** @return {Int} */
function toInt(val) {
return /** @type {Int} */ (val|0);
}
Int通常可分配给“数字”(它是一个数字),但“数字”不能在没有强制(强制转换)的情况下分配给“Int”。