Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSDoc type for multiple vars

I am writing a JavaScript module and I would like to write a good JSDoc for it. I have a multiple variables defined within single var (var x = 1, y = functionA; etc.). One of those variables holds a function reference (may have only 3 choices).

Now my question: is there a way to document it like above, so that my IDE (WebStorm) also recognize the variable type (atm. I get a warning when assigning other function reference to this variable)?

like image 245
Dracco Avatar asked Apr 26 '14 08:04

Dracco


2 Answers

Try using inline doc comments for this, like:

var /**Number*/ num = 1, /**String*/ str = "";
like image 156
lena Avatar answered Sep 21 '22 18:09

lena


This is the correct JSDoc syntax which will work just fine in Webstorm for auto-completion and type checking:

let 
    /** @type {Number} */ someNumber, 
    /** @type {String} */ someString;

Try setting a string to someNumber and see Webstorm complaining about it:

enter image description here

For functions, you can also specify its parameters and its return value. For instance:

/** @type {function(Number, String): Number[]} */

Is a function that receives a number as first param, a string as second and returns an array of numbers.

Note: although it works pretty well for auto-completion, currently Webstorm fails to do type checking for functions. For instance, it allows me to do this:

enter image description here

like image 42
Lucio Paiva Avatar answered Sep 21 '22 18:09

Lucio Paiva