Cómo documentar un tipo de cadena en jsdoc con valores posibles limitados
Tengo una función que acepta un parámetro de cadena. Este parámetro solo puede tener uno de los pocos valores posibles definidos. ¿Cuál es la mejor manera de documentar lo mismo? ¿Debe definirse shapeType como enum o TypeDef o algo más?
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;
};
La segunda parte del problema es que los posibles valores de shapeType
no se conocen en el archivo que define shapeType
como lo que sugiera. Hay varios archivos aportados por varios desarrolladores que podrían agregar a los posibles valores de shapeType
.
PS: Estoy usando jsdoc3
5 answers
¿Qué tal declarar una enumeración ficticia?:
/**
* 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)
Necesitas al menos declarar la enumeración a JSDOC, para esto, sin embargo. Pero el código está limpio y obtienes autocompletado en WebStorm.
El problema de los archivos múltiples, sin embargo, no se puede resolver de esta manera.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-11 16:09:51
A partir de finales de 2014 en jsdoc3 tienes la posibilidad de escribir:
/**
* @param {('rect'|'circle'|'ellipse')} shapeType - The allowed type of the shape
*/
Shape.prototype.getType = function (shapeType) {
return this.type;
};
Por supuesto, esto no será tan reutilizable como una enumeración dedicada, pero en muchos casos una enumeración ficticia es un exceso si solo es utilizada por una función.
Véase también: https://github.com/jsdoc3/jsdoc/issues/629#issue-31314808
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-12 13:19:53
No creo que haya una forma formal de escribir valores permitidos en JSDoc.
Ciertamente puedes escribir algo como @param {String('up'|'down'|'left'|'right')}
como el usuario b12toaster mencionado.
Pero, tomando referencia de APIDocjs, esto es lo que uso para escribir valores restringidos, también conocido como allowedValues.
/**
* Set the arrow position of the tooltip
* @param {String='up','down','left','right'} position pointer position
*/
setPosition(position='left'){
// YOUR OWN CODE
}
Oh sí, estoy usando ES6.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:57
Así es como el Compilador de Cierre lo soporta: puede usar "@enum" para definir un tipo restringido. En realidad no tiene que definir los valores en la definición de enumeración. Por ejemplo, podría definir un tipo "entero" como:
/** @enum {number} */
var Int = {};
/** @return {Int} */
function toInt(val) {
return /** @type {Int} */ (val|0);
}
Int es generalmente asignable a "number" (es un número) pero "number" no es asignable a "Int" sin alguna coerción (un cast).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-30 23:35:52
¿Qué pasa con:
/**
* @typedef {"keyvalue" | "bar" | "timeseries" | "pie" | "table"} MetricFormat
*/
/**
* @param format {MetricFormat}
*/
export function fetchMetric(format) {
return fetch(`/matric}`, format);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-19 08:14:07