Documenting a private constructor with JSDoc - javascript

I've got a class where individual methods may be called statically but will return a new instance of class in order to chain, for example:
var builder = ns
.setState('a', 'A')
.setState('b', 'B');
Where Builder is defined as such:
/**
* #module Builder
*/
/**
* #class Builder
*/
/**
* #private
*/
function Builder() {
this.state = {
query: {}
};
}
Builder.prototype = {
/**
* #param {string} k - The key
* #param {object} v - The value
* #return {Builder}
*/
setState: function(k, v) {
var that = (this instanceof Builder) ? this : new Builder();
that[k] = v;
return that;
}
// Other properties and methods…
}
The Builder constructor is never supposed to be called explicitly by user code and thus I'd like it not to show up in the docs. However, all of the combinations I've tried with JSDoc tags (e.g. #private, #constructs, etc.) can't seem to suppress it from the built docs.

From version 3.5.0 of jsDoc, you can use tag #hideconstructor on the class, telling jsDoc not to include the constructor into documentation.
/**
* #class Builder
*
* #hideconstructor
*/
function Builder() {
// implementation
}

You should be able to use the #ignore directive to achieve this. From the docs:
The #ignore tag indicates that a symbol in your code should never appear in the documentation. This tag takes precedence over all others.
http://usejsdoc.org/tags-ignore.html

Related

Type information for a conditional property in JSDoc

I'm adding type information for TypeScript to an existing JavaScript library via JSDoc. I have a constructor function that might set a property based on the value(s) of the parameter(s) it's given:
/**
* Settings you can use to configure an instance of an {#link ExampleClass}
*
* #typedef {Object} ExampleOptions
* #property {true} [option] You can set this to `true` to make a property on an instance of {#link ExampleClass} exist. If you don't set it, that property won't exist
*/
/**
* A thing that does stuff
*
* #constructor
* #param {ExampleOptions} [param] Options you can use to configure the new instance
*/
function ExampleClass(param) {
if(param.option === true) {
/**
* A property that only exists based on the options given to this constructor
*
* #type {boolean}
*/
this.property = true;
}
}
I was hoping that TypeScript would externally interpret the declaration of property to be like property?: boolean;, but it looks like it gets interpreted to be non-optional, and comes up in the autocomplete in my editor without having to check for its existence ahead of time. Ideally, I'd like for it to be an optional property that you'd have to check for before you can use it, or even allow you to use it unchecked if TypeScript can somehow guarantee that you had passed {option: true} to the constructor. How can I make that work?
Pre-declare the class with a #typedef with the optional properties and set it to the constructor as a variable of type {new () => ExampleClass}. This way it's even possible to declare this as the defined class and have code completion inside the constructor function itself. Something like the below:
/**
* Settings you can use to configure an instance of an {#link ExampleClass}
*
* #typedef {Object} ExampleOptions
* #property {true} [option] You can set this to `true` to make a property on an instance of {#link ExampleClass} exist. If you don't set it, that property won't exist
*/
/**
* #typedef {object} ExampleClass
* #prop {boolean} [property] A property that only exists based on the options given to this constructor
*/
/**
* A thing that does stuff
*
* #constructor
* #param {ExampleOptions} [param] Options you can use to configure the new instance
* #this {ExampleClass}
* #type {{new () => ExampleClass}}
*/
const ExampleClass = function (param) {
if(param.option === true) {
this.property = true;
}
}
Can you not just do
interface options {
option? : boolean;
}
/**
* A thing that does stuff
*
* #constructor
* #param {options} [param] Options you can use to configure the new instance
*/
function ExampleClass(param : options) {
if(param.option === true) {
/**
* A property that only exists based on the options given to this constructor
*
* #type {boolean}
*/
this.property = true;
}
}

ES6 Symbol properties not detected by Visual Studio Code Intellisense

I have the following two objects in Visual Studio Code, each with one public and one private (via symbol) method:
const symKey = Symbol();
/** #namespace */
var objLiteral = {
literalPublicFn1() {},
/**
* You found the secret fn!
*/
[symKey]() {},
};
/** #namespace */
var objAssigned = {};
/** #memberof objAssigned */
objAssigned.laterPublicFn1 = function() {};
/**
* You found the secret fn!
* #memberof objAssigned
* */
objAssigned[symKey] = function () {}
For both objects, the public methods are autocompleted accurately. However, when I try to access their private methods, autocompletion only works for the object literal:
Whereas for the later-assigned object, no autocompletion appears whatsoever.
Any solutions to this, or is this just a limitation of VSC's intellisense?

Annotate generic ES6 class with JSDoc

I want to document a generic map-like data structure with JSDoc. First of all, note that this structure does not extend Map.
A more general question would be: How do I annotate a generic ES6 class construct correctly?
Consider the following code. The marked piece of the annotation produces the error in the comment.
/** #type {MyMap<string, number>} */
// ^^^^^^^^^^^^^^^^^^^^^ [js] Type 'MyMap' is not generic.
const map = new MyMap();
That’s the definition of MyMap:
// #ts-check
/**
* #template K, V
*/
class MyMap {
constructor() {
this._map = new Map();
}
}
What do I need to do so that MyMap counts as a generic type? How do I expose K and V as the generic types of the structure?
(Note: I use Visual Studio Code to verify the annotations by adding // #ts-check to the top of my JavaScript file.)
First of all, as stated in the question, the #template annotation to make the MyMap class generic is already correct. Below, MyMap has two generic types Key and Value. Those types can be used inside the class, for example, by setting the type of the instance property this._map to /** #type {Map<Key, Value>} */, etc. To demonstrate, I added two simple wrapper methods around Map.prototype.set and Map.prototype.get that rely on those types.
// #ts-check
/**
* #template Key, Value
*/
class MyMap {
constructor() {
/** #type {Map<Key, Value>} */ this._map = new Map();
}
/**
* #param {Key} key
* #param {Value} value
*/
set(key, value) {
this._map.set(key, value)
}
/**
* #param {Key} key
* #returns {Value | undefined}
*/
get(key) {
return this._map.get(key)
}
}
/** #type {MyMap<string, number>} */ const map = new MyMap();
map.set('key', 1)
map.get('key')

Documenting the return of a javascript constructor with jsdoc

I have a javascript function that returns a constructor (see code sample below). How would I document this with the #returns tag of jsdoc. It doesnt seem correct to do #returns {MyConstructor} because that implies I am returning an instance of "MyConstructor" rather than the constructor itself, right?
function MyConstructor() {
var self = this;
self.myFunction = function() {
return true;
};
self.getMyFunctionResult = function() {
return self.myFunction();
};
}
/**
* #returns {?} A constructor that will be instantiated
*/
function getConstructor() {
return MyConstructor;
}
var constructor = getConstructor();
var instance = new constructor();
I do not think there is a way to use the brackets after #returns to document returning a specific instance. What goes in the brackets is interpreted as a type, always. This being said, there's a way to document that a specific instance of a type is being returned, by documenting the instance and using a link to the instance. I've shortened the code in the question to the essentials necessary to illustrate:
/**
* #class
*/
function MyConstructor() {
}
/**
* #returns {Function} A constructor that will be instantiated. Always
* returns {#link MyConstructor}.
*/
function getConstructor() {
return MyConstructor;
}
It can also be done with other things than classes:
/**
* #public
*/
var foo = 1;
/**
* #returns {number} {#link foo}.
*/
function getFoo(){
return foo;
}
As far as I know, this is as good as it gets with jsdoc 3.
Maybe little bit late, but I have problem to find proper answer for your question event today.
When I try generate JSDoc automatically on WebStorm, this is what I get:
class Test {}
/**
*
* #return {Test}
* #constructor
*/
function getTestConstructor() {
return Test;
}
Return type definition is still strange, but constructor annotation may fulfill the purpose.
You can check the types returned by your functions using:
console.log(typeof constructor, typeof instance); // function object
In the documentation it says:
/**
* Returns the sum of a and b
* #param {Number} a
* #param {Number} b
* #returns {Number} Sum of a and b
*/
function sum(a, b) {
return a + b;
}
http://usejsdoc.org/tags-returns.html
So in you example it would be:
/**
* Returns the MyConstructor class
* #returns {Function} MyConstructor class
*/
function getConstructor() {
return MyConstructor;
}
Or if you are creating an instance of an Item:
/**
* Returns an instance of the MyConstructor class
* #returns {Object} MyConstructor instance
*/
function getInstance() {
return new MyConstructor();
}

How to document a Require.js (AMD) Modul with jsdoc 3 or jsdoc?

I have 2 types of Modules:
Require.js Main File:
require.config({
baseUrl: "/another/path",
paths: {
"some": "some/v1.0"
},
waitSeconds: 15,
locale: "fr-fr"
});
require( ["some/module", "my/module", "a.js", "b.js"],
function(someModule, myModule) {
}
);
Mediator Pattern:
define([], function(Mediator){
var channels = {};
if (!Mediator) Mediator = {};
Mediator.subscribe = function (channel, subscription) {
if (!channels[channel]) channels[channel] = [];
channels[channel].push(subscription);
};
Mediator.publish = function (channel) {
if (!channels[channel]) return;
var args = [].slice.call(arguments, 1);
for (var i = 0, l = channels[channel].length; i < l; i++) {
channels[channel][i].apply(this, args);
}
};
return Mediator;
});
How can i document this with jsdoc3 when possible with jsdoc too?
This is my first answer on SO, please let me know how I can improve future answers.
Your specific example
I've been searching for an answer for this for a good two days, and there doesn't seem to be a way to document RequireJS AMD modules automatically without some redundancy (like repeated function names). Karthrik's answer does a good job of generating the documentation, but if something gets renamed in the code the documentation will still be generated from what's in the jsDoc tags.
What I ended up doing is the following, which is adjusted from Karthik's example. Note the #lends tag on line 1, and the removal of the #name tag from the jsDoc comment blocks.
define([], /** #lends Mediator */ function(Mediator){
/**
* Mediator class
* This is the interface class for user related modules
* #class Mediator
*/
var channels = {};
if (!Mediator) Mediator = {};
/**
* .... description goes here ...
* #function
*
* #param {Number} channel .....
* #param {String} subscription ..............
* #example
* add the sample code here if relevent.
*
*/
Mediator.subscribe = function (channel, subscription) {
if (!channels[channel]) channels[channel] = [];
channels[channel].push(subscription);
};
Mediator.publish = function (channel) {
if (!channels[channel]) return;
var args = [].slice.call(arguments, 1);
for (var i = 0, l = channels[channel].length; i < l; i++) {
channels[channel][i].apply(this, args);
}
};
return Mediator;
});
From what I understand, the #lends tag will interpret all jsDoc comments from the next following object literal as part of the class referenced by the #lends tag. In this case the next object literal is the one beginning with function(Mediator) {. The #name tag is removed so that jsDoc looks in the source code for function names, etc.
Note: I've used the #exports tag at the same place as where I put the #lends tag. While that works, it'll create a module in the docs… and I only wanted to generate docs for the class. This way works for me!
General jsDoc references
jsdoc-toolkit Tag Reference - Great reference for the tags in jsdoc-toolkit. Has a bunch of examples, too!
2ality's jsDoc intro - Comprehensive tutorial based on jsDoc-toolkit.
jsDoc3 reference - Fairly incomplete, but has some examples.
jsDoc doesn't seem to like the "define" and "require" calls.
So, we ended up using multiple tags to make the jsDoc tool to pick up the constructor and other specific class methods. Please have a look at the example below:
I have just copy-pasted from my source-code and replaced it with your class name and method names. Hope it works for you.
define([], function(Mediator){
/**
* Mediator class
* This is the interface class for user related modules
* #name Mediator
* #class Mediator
* #constructor
* #return Session Object
*/
var channels = {};
if (!Mediator) Mediator = {};
/**
* .... description goes here ...
* #name Mediator#subscribe
* #function
*
* #param {Number} channel .....
* #param {String} subscription ..............
* #example
* add the sample code here if relevent.
*
*/
Mediator.subscribe = function (channel, subscription) {
if (!channels[channel]) channels[channel] = [];
channels[channel].push(subscription);
};
Mediator.publish = function (channel) {
if (!channels[channel]) return;
var args = [].slice.call(arguments, 1);
for (var i = 0, l = channels[channel].length; i < l; i++) {
channels[channel][i].apply(this, args);
}
};
return Mediator;
});
Note: The above method of documenting JS-code worked out well for us while using jsDoc. Haven't got a chance to try jsDoc3.
Taking the link from Muxa's answer, we see that the documentation does specifically refer to RequireJS:
The RequireJS library provides a define method that allows you to write a function to return a module object. Use the #exports tag to document that all the members of an object literal should be documented as members of a module.
Module Example
define('my/shirt', function () {
/**
* A module representing a shirt.
* #exports my/shirt
* #version 1.0
*/
var shirt = {
/** A property of the module. */
color: "black",
/** #constructor */
Turtleneck: function(size) {
/** A property of the class. */
this.size = size;
}
};
return shirt;
});
So in the above example, we see that jsdoc will parse a my/shirt module and document it as having two members: a property color, and also a class Turtleneck. The Turtleneck class will also be documented as having it's own property size.
Constructor Module Example
Use the #alias tag simplify documenting a constructor-module in RequireJS.
/**
* A module representing a jacket.
* #module jacket
*/
define('jacket', function () {
/**
* #constructor
* #alias module:jacket
*/
var exports = function() {
}
/** Open and close your Jacket. */
exports.prototype.zip = function() {
}
return exports;
});
The above is what you'd want to use if you are exporting a constructor function as the module which will be used as a class to instantiate objects. To sum up, I'm not sure about using the #lends and other tags/techniques that have been recommended. Instead, I would try to stick with the #module, #exports, and #alias tags used in the documentation referencing RequireJS.
I'm not sure how you should document your requirejs 'main' file. If I understand correctly, you are not actually defining any module there, but rather executing a one off function which depends on several modules.
My AMD classes use a slightly different form, but JSDoc wasn't documenting them either so I thought I'd share what worked for me.
Constructors in the global namespace are automatically added:
/**
* #classdesc This class will be documented automatically because it is not in
* another function.
* #constructor
*/
function TestClassGlobal() {
/**
* This is a public method and will be documented automatically.
*/
this.publicMethod = function() {
};
}
If you want this behavior on a constructor inside an AMD module, declare it either as global or a member of a namespace:
define([], function() {
/**
* #classdesc This won't be automatically documented unless you add memberof,
* because it's inside another function.
* #constructor
* #memberof Namespace
*/
function TestClassNamespace() {
}
/**
* #classdesc This won't be automatically documented unless you add global,
* because it's inside another function.
* #constructor
* #global
*/
function TestClassForcedGlobal() {
}
});
Looks like things have gotten a lot simpler in JSDoc3. The following worked for me:
Mediator as a module
/**
* Mediator Module
* #module Package/Mediator
*/
define([], function(Mediator){
var channels = {};
if (!Mediator) Mediator = {};
/**
* Subscribe
* #param {String} channel Channel to listen to
* #param {Function} subscription Callback when channel updates
* #memberOf module:Package/Mediator
*/
Mediator.subscribe = function (channel, subscription) {
if (!channels[channel]) channels[channel] = [];
channels[channel].push(subscription);
};
/**
* Publish
* #param {String} channel Channel that has new content
* #memberOf module:Package/Mediator
*/
Mediator.publish = function (channel) {
if (!channels[channel]) return;
var args = [].slice.call(arguments, 1);
for (var i = 0, l = channels[channel].length; i < l; i++) {
channels[channel][i].apply(this, args);
}
};
return Mediator;
});
However, I would probably make the following change to the code:
/**
* Mediator Module
* #module Package/Mediator
*/
define([], function(){
var channels = {};
var Mediator = {}
...
Reason is, the module says it defines Mediator, but seems to borrow from some other instance of Mediator. I'm not sure I understand that. In this version, it's clear Mediator is defined by this file and exported.

Categories

Resources