Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum as @param type in JSDoc

Is it possible to use an enum for the JSDoc @param type declaration like 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 no warning be raised?

like image 719
BuZZ-dEE Avatar asked Feb 11 '14 13:02

BuZZ-dEE


People also ask

Can you use JSDoc with TypeScript?

You can use most JSDoc type syntax and any TypeScript syntax, from the most basic like string to the most advanced, like conditional types.

Does TypeScript have enums?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

Is JSDoc useful?

Using TypeScript consistently offers a lot of benefits, especially for writing clean code to prevent unnecessary bugs and errors.


2 Answers

You can achieve that, by doing this:

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

enter image description here

like image 130
Ahmed Mahmoud Avatar answered Sep 19 '22 21:09

Ahmed Mahmoud


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

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

This means:

  • MyType is a number
  • TYPES is an enum that holds MyType values
  • This function accepts enums that output MyType values

Works for me on intellij 2017.1

However - this will still allow each string to be passed to the function without warnings.

If you want to specify the enum values too - so it should raise errors if another string was used, use the method described at: 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"     */ 
like image 35
guy mograbi Avatar answered Sep 21 '22 21:09

guy mograbi