I am trying to use JsDoc to document es6 classes. Can't believe that you can't pass a class as a parameter (a class type, not an instance type).
I've been trying things but can't get this simple code to work so that JsDoc doesn't throw me some warnings.
I can't get it to work unless I create a #typedef for each of my classes, then add manually all own and inherited members to it. Can't even do a mixin!
Has anyone succeeded in passing a constructor/class parameter? So that JsDoc be in the static context, not the instance context?
/**
* #class A
*/
class A {
/**
* #static
*/
static helloFromClassA(){
}
}
/**
* #class B
* #extends A
*/
class B extends A{
/**
* #static
*/
static helloFromClassB(){
}
}
/**
* Class as object
* #param {A} ClassArgument
*/
function fn1(ClassArgument){
ClassArgument.helloFromClassA(); // Unresolved function or method helloFromClassA
// Does not work because ClassArgument is interpreted as an
// instance of A, not A's constructor
}
/**
* // Class as function
* #param {Function} ClassArgument
*/
function fn2(ClassArgument){
ClassArgument.helloFromClassA(); // Unresolved function or method helloFromClassA
// Does not work because ClassArgument is interpreted as an
// empty function, not A's constructor
}
/**
* // Type definition
* #typedef {Object} AClass
* #property {Function} helloFromClassA
* #property {Function} super
*/
/**
* // Trying to mixin the AClass
* #typedef {Object} BClass
* #property {Function} helloFromClassB
* #mixes {AClass}
* #mixes {A}
*/
/**
* // Adding manually all members
* #typedef {Object} BClass2
* #property {Function} helloFromClassB
* #property {Function} helloFromClassA
*/
/**
* #param {BClass} ClassArgument
*/
function fn3(ClassArgument){
ClassArgument.helloFromClassA(); // Unresolved function or method helloFromClassA
// Does not work because the BClass typedef does not take
// into account the mixin from AClass, nor from A
ClassArgument.helloFromClassB(); // No warming
}
/**
* #param {BClass2} ClassArgument
*/
function fn4(ClassArgument){
ClassArgument.helloFromClassA(); // No Warning
ClassArgument.helloFromClassB(); // No warming
// Works because we manually defined the typedef with all own
// and inherited properties. It's a drag.
}
fn1(B);
fn2(B);
fn3(B);
fn4(B);
jsDoc issue : https://github.com/jsdoc3/jsdoc/issues/1088
I've been running into same issue with auto-completion in WebStorm multiple times. While it looks like currently there is no straight-forward way in jsdoc to say that parameter is a reference to a constructor (not to an instance), there is a suggestion from JetBrains team to implement something like #param {typeof Constructor} (where typeof is from typescript) or #param {Constructor.} that was suggested by closure compiler team. You can vote for following issue to get your main concern with WebStorm autocompletion resolved - https://youtrack.jetbrains.com/issue/WEB-17325
In Visual Studio Code, you can specify
#param {function(new:MyClass, SomeArgType, SecondArgType, etc...)}
I'm not sure what spec that syntax comes from or who else supports it, but it Works For Me.
typescript and google closure both support {typeof SomeClass} for referencing a class as a type (not a class instance). Unfortunately jsdoc doesn't support that syntax and will fail to compile it (https://github.com/jsdoc3/jsdoc/issues/1349).
Because I want to type-checking my JavaScript with typescript and also want to generate documentation I made this jsdoc plugin to transform expressions like {typeof SomeClass} into {Class<SomeClass>} so I can have both things: https://github.com/cancerberoSgx/jsdoc-typeof-plugin
Related
Background
I have a project in Nodejs using ECMA6 classes and I am using JSDoc to comment my code, as to make it more accessible to other developers.
However, my comments are not well accepted by the tool, and my documentation is a train wreck.
Problem
My problem is that I don't know how to document ECMA6 classes with JSDoc and I can't find any decent information.
What I tried
I tried reading the official example but I find it lacking and incomplete. My classes have members, constant variables and much more, and I don't usually know which tags to use for what.
I also made an extensive search in the web, but most information I found is prior to 2015 where JSDocs didn't support ECMA6 scripts yet. Recent articles are scarce and don't cover my needs.
The closest thing I found was this GitHub Issue:
https://github.com/jsdoc3/jsdoc/issues/819
But it is outdated by now.
Objective
My main objective is to learn how to document ECMA6 classes in NodeJS with JSDoc.
I have a precise example that I would like to see work properly:
/**
* #fileOverview What is this file for?
* #author Who am I?
* #version 2.0.0
*/
"use strict";
//random requirements.
//I believe you don't have to document these.
let cheerio = require('cheerio');
//constants to be documented.
//I usually use the #const, #readonly and #default tags for them
const CONST_1 = "1";
const CONST_2 = 2;
//An example class
class MyClass {
//the class constructor
constructor(config) {
//class members. Should be private.
this.member1 = config;
this.member2 = "bananas";
}
//A normal method, public
methodOne() {
console.log( methodThree("I like bananas"));
}
//Another method. Receives a Fruit object parameter, public
methodTwo(fruit) {
return "he likes " + fruit.name;
}
//private method
methodThree(str) {
return "I think " + str;
}
}
module.exports = MyClass;
Question
Given this mini class example above, how would you go about documenting it using JSDoc?
An example will be appreciated.
Late answer, but since I came across this googling something else I thought I'd have a crack at it.
You've probably found by now that the JSDoc site has decent explanations and examples on how to document ES6 features.
Given that, here's how I would document your example:
/**
* module description
* #module MyClass
*/
//constants to be documented.
//I usually use the #const, #readonly and #default tags for them
/** #const {String} [description] */
const CONST_1 = "1";
/** #const {Number} [description] */
const CONST_2 = 2;
//An example class
/** MyClass description */
class MyClass {
//the class constructor
/**
* constructor description
* #param {[type]} config [description]
*/
constructor(config) {
//class members. Should be private.
/** #private */
this.member1 = config;
/** #private */
this.member2 = "bananas";
}
//A normal method, public
/** methodOne description */
methodOne() {
console.log( methodThree("I like bananas"));
}
//Another method. Receives a Fruit object parameter, public
/**
* methodTwo description
* #param {Object} fruit [description]
* #param {String} fruit.name [description]
* #return {String} [description]
*/
methodTwo(fruit) {
return "he likes " + fruit.name;
}
//private method
/**
* methodThree description
* #private
* #param {String} str [description]
* #return {String} [description]
*/
methodThree(str) {
return "I think " + str;
}
}
module.exports = MyClass;
Note that #const implies readonly and default automatically. JSDoc will pick up the export, the #class and the #constructor correctly, so only the oddities like private members need to be specified.
For anyone visiting this question in 2019:
The answer given by #FredStark is still correct, however, the following points should be noted:
Most/all of the links in this page are dead. For the documentation of the JSDoc, you can see here.
In many IDEs or code editors (such as VSCode), you will find auto-completions such as #class or #constructor which are not necessary for the case of ES6 classes since these editors will recognize the constructor after the new keyword.
Currently using Webstorm in a project with Dojo (1.10), and ESRI API Javascript.
I have a function that accept a Widget (Object/Class), but the Webstorm show me some warnings because of JSDoc.
Code:
/**
* Init toolbar
*
* #param {Object} [options] - Toolbar options
* #param {string} [options.title=Default title] - Main title
* #param {ToolbarWidget} toolbarObj - Toolbar widget to set
*/
initToolbar: function(options, toolbarObj) {
...
toolbarObj.set('title', _title);
}
The first warning was on 'toolbarObj'. I get a message 'Unresolved variable or type'.
This was easy to resolve. Just included the following JSDoc:
/**
* A dojo widget (toolbar).
* #typedef {Object} ToolbarWidget
*/
Now, the another warning was the 'set' function of toolbarObj.
I get a warning with the following message: 'unresolved function or method set()'.
Already tried #name, #function (maybe not in the correct way)!
I known this is optional (is just a warning), but, I like to document everything in the right way.
So, how I can document the 'set' function of a anonymous object/dojo widget?!
What about
/**
* A dojo widget (toolbar).
* #typedef {Object} ToolbarWidget
* #property {function} set
*/
I have decided to use JSDoc to document a project I am working on. While reading the usage guide and questions here I still feel that I am not grasping some of the core concepts of JSDoc and I illustrated my incompetence in the following example: http://jsfiddle.net/zsbtykpv/
/**
* #module testModule
*/
/**
* #constructor
*/
var Test = function() {
/**
* #callback myCallback
* #param {Object} data An object that contains important data.
*/
/**
* A method that does something async
* #param {myCallback} cb a callback function
* #return {boolean} always returns true
*/
this.method = function(cb) {
doSomethingAsync(function(data) {
cb(data);
});
return true;
}
}
module.exports = Test;
Here, I have defined a module, indicated a constructor, and documented a method that takes a callback as one of its' parameters. Sounds pretty simple and appears to follow the guidelines set by the usage guide http://usejsdoc.org/.
But for some reason beyond my understanding (and that's probably the core concept I'm not getting), it shows the callback myCallback as a member of the testModule instead of the Test class. Shouldn't it default to be a member of the class and not the module? This also appears to prevent JSDoc from making a link to the callback definition, which is not a lot of fun.
Now I realize that if I were to write:
/**
* #callback module:testModule~Test~myCallback
* #param {Object} data An object that contains important data.
*/
/**
* A method that does something async
* #param {module:testModule~Test~myCallback} cb a callback function
* #return {boolean} always returns true
*/
I would get my desired behavior. But this seems to be a very clunky way of doing things and the generated links are far from pretty.
Sorry for the long buildup and thank you in advance for your help in my documentation effort :)
I have come across much the same problem. If you want nicer-looking links, you can always add a {#link} in the description and just use the canonical name in the #type like this:
/**
* #callback module:testModule~Test~myCallback
* #param {Object} data An object that contains important data.
*/
/**
* #param {myCallback} cb {#link module:testModule~Test~myCallback|myCallback}: a callback function
* #return {boolean} always returns true
*/
I realize that's a bit more frustrating to type, but it documents myCallback as a member of the class rather than the module, and the link looks nice.
If you really want the link in the #type and you don't care about how it documents the callback, you could also do this, which is a little less verbose (and what I've decided to do for my project):
/**
* #callback myCallback
* #param {Object} data An object that contains important data.
*/
/**
* #param {module:testModule~myCallback} cb a callback function
* #return {boolean} always returns true
*/
That will properly link to myCallback and document it as a member of the module.
I compile my source with closure compiler and when i call a function that got an event object from network the application throws an error in console.
The function called is:
/**
* #param {goog.events.Event} event Socket.io-Wrapper Event.
*/
de.my.app.admin.prototype.onSaved = function(event){
var category = event.data[0].category; //<-- here it throws the error because category get compiled.
var id = event.data[0].id;
var oldid = event.data[0].oldid;
[...]
}
the event object looks like this
{ data:{
0: {
category: 'someString',
id: 5,
oldid: -5
} }
[...someMoreValuesAddedBySocketIO...]
}
that is the behavior i expected.
now i add an externs declaration like this to my externs file but i didn't alter the type declaration of the #param at the function and the error disappears:
var xterns;
/**
* #typedef {{
* category : string,
* oldid : number,
* id : number
* }}
*/
xterns.NOTUSEDNAME;
/**
* #type {string}
*/
xterns.NOTUSEDNAME.prototype.category;
/**
* #type {number}
*/
xterns.NOTUSEDNAME.prototype.oldid;
/**
* #type {number}
*/
xterns.NOTUSEDNAME.prototype.id;
In short: I have a #param {goog.events.Event} event declaration and an extern for xterns.NOTUSEDNAME solves the compiler problems...
Can anyone explain why this happens?
This is a common misconception. Closure-compiler will not rename a property if any extern object contains a property of the same name. See the FAQ. If the type based optimizations are enabled, then this is no longer true and I would expect your code to break again.
To make this code type safe and compile without warnings, you would need to either:
Reference the data properties using quoted syntax event.data[0]['category']. Your properties will never be renamed by the compiler using this method (which is often used by JSON Data).
Extend the goog.events.Event type with a custom object that defines the data object as a strongly typed array.
Example:
/**
* #constructor
* #extends {goog.events.Event}
*/
de.my.app.AdminEvent = function() {};
goog.inherits(de.my.app.AdminEvent, goog.events.Event);
/** #type {Array.<{category:string, id:number, oldid:number}>} */
de.my.app.AdminEvent.prototype.data = [];
Depending on your exact situation, an interface might be a better option.
I have a JavaScript singleton object created with closure method:
/**
* This is the singleton.
*
* #namespace window.Something.Singleton
*/
window.Something.Singleton = (function() {
/**
* Foo method.
*
* #return {String} this method always returns with <code>bar</code>
*/
function _foo() { return "bar"; }
/**
* #lends window.Something.Singleton#
*/
return {
/**
* #borrows window.Something-_foo
* #function
*/
foo: _foo
};
}());
But the jsdoc-toolkit does not generate the inherited documentation from _foo method to the foo method what I would like to have.
If I write #see instead of #borrows it works (inserts a link to the correct method), but I don't want to copy&paste the documentation for the foo method to have a public documentation as well.
I did some tests, and I have good news and bad news :). The good news is that it looks like you can get this to work by putting the #borrows tag in the Singleton doc comment:
/**
* This is the singleton.
*
* #namespace Something.Singleton
* #borrows Something.Singleton-_foo as foo
*/
Something.Singleton = (function() {
// etc
})());
But this has several ramifications, good and bad:
The foo function is marked static. This is probably a good thing, as it seems to be accurate as I understand your code.
With the code as it is currently shown (i.e. no more methods on the singleton, etc), you can dispense with the #lends tag entirely, unless you want to include it for clarity. If all methods are listed as #borrows on the top singleton namespace, then you don't need to further document them in the returned object. Again, this is probably a good thing.
The bad news is that I couldn't get this to work unless the borrowed method was explicitly marked #public - which makes it show up, redundantly, in the documentation. I think this is unavoidable - if jsdoc-toolkit thinks the method is private, it won't create documentation, so you can't refer to it (I get WARNING: Can't borrow undocumented Something.Singleton-_foo.). If the method is public, it gets displayed in the documentation.
So this works:
/**
* This is the singleton.
*
* #namespace Something.Singleton
* #borrows Something.Singleton-_foo as foo
*/
Something.Singleton = (function() {
/**
* #public
* Foo method.
*
* #return {String} this method always returns with <code>bar</code>
*/
function _foo() { return "bar"; }
return {
foo: _foo
};
}());
...in that it copies the documentation for _foo to foo, but it will display _foo in the documentation page as well:
Method Summary
<inner> _foo()
<static> Something.Singleton.foo()
Probably the best workaround is simply to forget #borrows entirely and explicitly name _foo as Something.Singleton.foo in the doc comment, marking it as a public function (you could dispense with #public if you didn't name your inner function with an underscore, but this tells jsdoc-toolkit to treat it as private unless told otherwise):
/**
* This is the singleton.
*
* #namespace Something.Singleton
*/
Something.Singleton = (function() {
/**
* #name Something.Singleton#foo
* #public
* #function
* Foo method.
*
* #return {String} this method always returns with <code>bar</code>
*/
function _foo() { return "bar"; }
return {
foo: _foo
};
}());
This will produce the code documentation you're looking for, and puts the comment next to the actual code it relates to. It doesn't fully satisfy one's need to have the computer do all the work - you have to be very explicit in the comment - but I think it's just as clear, if not more so, than what you had originally, and I don't think it's much more maintenance (even in your original example, you'd have to change all your doc comments if you renamed Something.Singleton).
http://code.google.com/p/jsdoc-toolkit/wiki/TagBorrows
#borrows otherMemberName as thisMemberName
otherMemberName - Required: the namepath to the other member.
thisMemberName - Required: the new name that the member is being assigned to in this class.
/** #constructor */
function Remote() {
}
/** Connect to a remote address. */
Remote.prototype.transfer = function(address, data) {
}
/**
* #constructor
* #borrows Remote#transfer as this.send
*/
function SpecialWriter() {
this.send = Remote.prototype.transfer;
}
Any documentation for Remote#transfer will also appear as documentation for SpecialWriter#send.