Enum as @param type in JSDoc

Can I use an enumeration to declare a JSDoc @param type, as in the following example?

 /** * @enum { Number } */ var TYPES = { TYPE_A: 1, TYPE_B: 2 } /** * @param { TYPES } type */ function useTypesEnum( type ) { } 

If I use an IDE like Eclipse etc. for javascript there should be no warning?

+19
javascript ide jsdoc jsdoc3
source share
3 answers

JsDoc comments do not affect JavaScript code. What it affects are some of the tools designed to use this information. Two of the tools that work with JsDoc comments are the documentation generator and the Google Closure compiler.

I am not particularly familiar with JsDoc3, to which the @enum tag has been added, but I would suggest that it works the same as any other type.

The Closure compiler also correctly recognizes the enumeration, and you can use it in the same way as you mentioned in the example and get all the advantages of the compiler (for example: type checking).

+3
source share

So it seems like this is the right way to document everything without warning.

 /** * @typedef {number} MyType **/ /** * @enum {MyType} */ var TYPES = { TYPE_A: 1, TYPE_B: 2 } /** * @param {MyType} type */ function useTypesEnum( type ) { } 

It means:

  • MyType is a number
  • TYPES is an enumeration that contains MyType values
  • This function accepts enumerations that print MyType values.

Works for me on the website 2017.1

However, this will still allow passing each line to the function without warning.

If you also want to specify the values โ€‹โ€‹of the enumeration - therefore, it should raise errors if another line is used, use the method described at: https://stackoverflow.com/a/16729/

  /** * @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" */ 
+18
source share

You can achieve this by doing the following:

 /** * @param {(1|2)} type */ function useTypesEnum(type) { } 

enter image description here

+6
source share

All Articles