BuZ*_*dEE 22 javascript ide jsdoc jsdoc3
是否可以使用枚举作为JSDoc @param
类型声明,如下例所示?
/**
* @enum { Number }
*/
var TYPES = {
TYPE_A: 1,
TYPE_B: 2
}
/**
* @param { TYPES } type
*/
function useTypesEnum( type ) {
}
Run Code Online (Sandbox Code Playgroud)
如果我使用Eclipse之类的IDE等JavaScript,那么应该不会引发警告?
guy*_*abi 22
因此,这似乎是在没有任何警告的情况下记录所有内容的正确方法
/**
* @typedef {number} MyType
**/
/**
* @enum {MyType}
*/
var TYPES = {
TYPE_A: 1,
TYPE_B: 2
}
/**
* @param {MyType} type
*/
function useTypesEnum( type ) {
}
Run Code Online (Sandbox Code Playgroud)
这意味着:
适用于intellij 2017.1
但是 - 这仍然允许每个字符串在没有警告的情况下传递给函数.
如果您还要指定枚举值 - 如果使用另一个字符串,则应该引发错误,请使用以下描述的方法:https://stackoverflow.com/a/36501659/1068746
/**
* @typedef FieldType
* @property {string} Text "text"
* @property {string} Date "date"
* @property {string} DateTime "datetime"
* @property {string} Number "number"
* @property {string} Currency "currency"
* @property {string} CheckBox "checkbox"
* @property {string} ComboBox "combobox"
* @property {string} Dropdownlist "dropdownlist"
* @property {string} Label "label"
* @property {string} TextArea "textarea"
* @property {string} JsonEditor "jsoneditor"
* @property {string} NoteEditor "noteeditor"
* @property {string} ScriptEditor "scripteditor"
* @property {string} SqlEditor "sqleditor"
*/
Run Code Online (Sandbox Code Playgroud)
mii*_*le7 12
我使用以下内容:
const TYPES = {
0: "TYPE_A",
1: "TYPE_B"
}
/**
* @param {keyof TYPES} type
*/
function useTypesEnum(type) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
这显示了 VSCode 中建议的正确值。它具有很好的可读性,为开发人员提供了关于哪个值代表什么以及可以在运行时使用枚举值的线索。
如果我在运行时不需要 的值,我什TYPES
至更喜欢使用:TYPES
@typedef
/**
* @typedef {{
* 0: "TYPE_A",
* 1: "TYPE_B"
* }} TYPES
*/
/**
* @param {keyof TYPES} type
*/
function useTypesEnum(type) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
如果应该使用枚举的值,或者出于任何原因必须翻转枚举键和值,我会使用valueOf<T>
帮助器。缺点是,这在 VSCode 中不提供自动完成功能。但至少函数参数定义在某种程度上是可读的。
/**
* @typedef {T[keyof T]} valueOf<T>
* @template T
*/
const TYPES = {
"TYPE_A": 0,
"TYPE_B": 1
};
/**
* @param {valueOf<TYPES>} type
*/
function useTypesEnum(type) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
Ahm*_*oud 11
您可以通过执行以下操作来实现:
/**
* @param {(1|2)} type
*/
function useTypesEnum(type) {
}
Run Code Online (Sandbox Code Playgroud)
Tib*_*bos -7
JSDoc 注释对 JavaScript 代码没有影响。它真正影响的是一些旨在使用该信息的工具。处理 JSDoc 注释的两个工具是文档生成器和 Google Closure 编译器。
我对 JSDoc 3 不是特别熟悉,其中@enum
添加了标签,但我认为它与任何其他类型一样工作。
闭包编译器还可以enum
正确识别,您可以像示例中提到的那样使用它,并获得编译器的所有好处(例如:类型检查)。