I have such code:
var f = function(){
var obj = {};
obj.keyA = "val";
obj.keyB = function(arg2){}
return obj;
}
arg2 is a {string}.
Is it possible to describe this code fine using JSDoc?
As you see, this code is attemption to implement smth like an object-oriented code. It is because I should work with old JavaScript engine (ECMA 262 Edition 3, parts of Edition 4, 5 and 6). It seems, this engine does not support classes (an interpreter thrown a syntax error).
So, is it possible to describe the code above in a way that JSDoc generates readable documentation?
I'd suggest using a custom tag typedef which will allow you to describe inner type in the first place e.g.
/**
* Definition for keyB
* #callback KeyBCallback
* #param {*} arg2
* #returns {void}
*/
/**
* Definition of an internal obj
* #typedef {Object} InternalObj
* #property {string} keyA - some property
* #property {KeyBCallback} keyB - a callback stored in keyB
*/
Lastly, you need to put InternalObj as a return value for your function e.g.
/**
* Function f
* #returns {InternalObj}
*/
var f = function(){
var obj = {};
obj.keyA = "val";
obj.keyB = function(arg2){}
return obj;
}
Related
I am using Visual Studio Code version 1.17.1.
In *.js file when I type document.querySelector("#elementId").style. I have no IntelliSense hints for styles (like margin, display, etc.).
Even no onclick event hint after document.querySelector("#elementId").
I don't use any npm packages. It is just simple html\css\js project.
How to turn on correct IntelliSense hints? Thanks.
Because result of the querySelector is either:
Element - the most general base class or null
If you already know id you can use document.getElementById() - which returns instance of more specific class - HTMLElement - autocomplete will work as expected.
document.getElementById('elementId').
If you don't know id, but want autocomplete you can use JSDoc type annotations:
/** #type {HTMLElement} */
var el = document.querySelector(".myclass");
el.
// or without extra variable:
/** #type {HTMLElement} */
(document.querySelector(".myclass")).
I haven't really tested it but you can try something like that:
/**
* #type {function(string): HTMLElement}
*/
var querySelector = document.querySelector.bind(document);
querySelector('.myclass').
Another choice would be alter typescript types:
Create file dom.d.ts
Append to it:
interface NodeSelector {
querySelector<K extends keyof ElementTagNameMap>(selectors: K): ElementTagNameMap[K] | null;
querySelector<E extends HTMLElement = HTMLElement>(selectors: string): E | null;
querySelectorAll<K extends keyof ElementListTagNameMap>(selectors: K): ElementListTagNameMap[K];
querySelectorAll<E extends HTMLElement = HTMLElement>(selectors: string): NodeListOf<E>;
}
Now querySelector returns HTMLElement.
The other answer points to the correct answer – type casting with jsdoc – but I've found that this only works consistently when you do it exactly as typescript wants when dealing with union types: you need to wrap the casted expression in parentheses and place the type cast doc on the same line. The snippet from a permalink to the wiki:
// We can "cast" types to other types using a JSDoc type assertion
// by adding an `#type` tag around any parenthesized expression.
/**
* #type {number | string}
*/
var numberOrString = Math.random() < 0.5 ? "hello" : 100;
var typeAssertedNumber = /** #type {number} */ (numberOrString)
Can I define all custom types in a separate file (e.g. types.jsdoc), so that they can be reused throughout the application? What's the right way to do it?
/**
* 2d coordinates.
* #typedef {Object} Coordinates
* #property {Number} x - Coordinate x.
* #property {Number} y - Coordinate y.
*/
You can define types in a module (eg. typedefs.js). The module contains your JSDoc typdefs and can simply export an unused property.
// typedefs.js
/**
* #typdef foo
* #property {string} bar
*/
// etc.
exports.unused = {};
To use it, import the module where you need to reference these typdefs:
const typedefs = require("./typedefs");
/** #type {typedefs.foo} */
const fb = { bar: "hello" };
You may wish to annotate typedefs.js as a #module or #namespace. Because I'm using "tsd-jsdoc" to generate a types.d.ts file, and due to the way TypeScript now interprets modules vs. namespaces, I've annotated my typedefs.js file as a #namespace and documented each typedef as a member of that namespace:
/**
* #namespace typedefs
*/
/**
* #typedef foo
* #property {string} bar
* #memberof typdefs
*/
Hope that helps.
This is a TypeScript-flavored JSDoc specific answer, but I'm having success using a triple-slash directive to "import" all the types from another file. This has the advantage of not actually adding an unused import which can upset linters and bundlers.
I'm putting my shared types in one file called typedefs.js like this:
// typedefs.js
/**
* #typedef {Object} Foo
* #property {string} bar
*/
/**
* #typedef {Object} Baz
* #property {number} buzz
*/
and then using /// <reference path="typedefs.js" /> in the other files to access the shared types like this:
// randomThing.js
/// <reference path="typedefs.js" />
/**
* Turn a Foo into a Baz
*
* #param {Foo} a
* #return {Baz}
export function (a) {
return { buzz: a.bar.length };
}
The tricky thing though is that now typedefs.js is just being referenced in a comment, bundlers like rollup miss it completely. So I'm combining it with my old consts.js that exports a few constants and is imported in at least one place. That way the typedefs are still included in the rollup output.
I hope someone else finds this helpful.
p.s. rollup will completely exclude a pure JSDoc typedefs.js file _even if you have import './typedefs.js' because of tree-shaking! Gotta run rollup with --no-treeshake to keep those comments in the rollup output.
In vscode, the import('./path/to/types.js').def tag works perfectly fine.
For e.g.
types.js
/**
* #typedef {Object} connection
* #property {String} id
* #property {Number} pingRetries
* #property {(data:Object) => void} sendJSON
*/
exports.unused = {};
And someFile.js
/**
* #param {import('./types').connection} param
*/
const someFunc = (param) => {}
Also, note that the exports.unused = {} is necessary in the types.js file, otherwise the auto-import of import('./types') would not work and you may have to type it by yourself.
I just tried with VSCode and it works only if the separate file is opened in the editor. If not, external typedefs are typed as any
I usually do something similar in my projects, the difference being I use the extension .js to name the file. Webstorm works perfectly and is able to check types and auto-complete just fine. It won't recognize the .jsdoc extension (I just checked), so stick to .js even if the file doesn't contain any code statement.
I've had success with simply creating my types in a typedefs.js file and referencing using the ts/vscode import(path/to/file).Foo tag. JSDoc does not support this syntax out of the box, so I suggest also using jsdoc-tsimport-plugin in order to parse your docs.
Eg: typedef.js:
/**
* #typedef {Object} Foo
* #property {string} id
*/
/**
* #typedef {Object} Bar
* #property {string[]} things
*/
// having to export an empty object here is annoying,
// but required for vscode to pass on your types.
export {};
coolFunction.js
/**
* This function is super dope
* #param {import('../typedef').Foo[]} foo - a foo
* #return {import('../typedef').Bar[]} bar - an array of bars
*/
export function (foo) {
// do cool things
return bar;
}
I'm also using tsd-jsdoc to create a types.d.ts file, and this implementation is successfully creating the types. I had trouble with declaring modules and namespaces with the types file— just creating standalone typedefs for said models worked best for me.
I have been having a hard time getting the #borrows tag working in JSDoc. I have been trying to get the documentation from one function and us it as documentation for a second function. But I don't seem to be able to even get a simple example working!
/**
* This is the description for funcA
*/
var funcA = function() {};
/**
* #borrows funcA as funcB
*/
var funcB = function() {};
I was expecting this to output documentation for both functions with both exactly the same. However only funcA is only has a description.
The #borrows tag doesn't seem to work directly on a symbol, but only indirectly. For example I had:
/** does amazing things */
function origFunc = function() {};
/**
* #borrows origFunc as exportedFunc
*/
exports.exportedFunc = origFunc;
but I, like you, got nothing useful in the generated doc.
That is because, it seems, that the #borrows tag operates on a container. (If you'll notice in the examples the #borrows tag is on the "util" module/namespace, not the renamed symbol.)
So this worked for me:
/** does amazing things */
function origFunc = function() {};
/**
* #borrows origFunc as exportedFunc
*/
exports = {
exportedFunc: origFunc,
}
Seems like a bug in #borrows though. (Or at least a bug in the documentation.)
I recently had a usage of it, what I was trying to do is to create a module and add some functions to it. The problem is that I don't have anything directly related to this module, since the export is just a line. Here's how I ended up with using #borrows.
/**
* A typehead with options filtered by user input.
*
* #module Typehead
* #borrows Typehead
* #borrows TypedOption
* #example
* <Typehead />
*/
export { default } from './Typehead'
In this case, Typehead will be borrowed in either Function or Classes section of module page depending on the kind of Typehead, and it will be displayed under #example render.
Note: However #borrows will add some extra entries to the system, after some experimentation, maybe #see is a better use.
I'm an absolute newcomer to JSDoc and the Javadoc-like conventions; I am looking for some low-hanging fruit to get up and running, and I'm coming up short.
My code is organized like this, primarily as a matter of personal style:
var app = app || {};
app.ui = {
someUIfunction: function() {},
someUIparams: {},
anotherFunction: function(string, object) {}
}
app.rest = {
someRESTCall: function(url,data) {},
someRESTparams: {},
moreRESTCall: function(url,data) {}
}
Theoretically everything could just be one monolithic object under "app", but I like breaking down the next-level objects separately for handy cold-folding and searching in the IDE. Plus it just feels tidy to me that way.
What I cannot manage to do is drill down into the third-level functions and objects. JSDoc3 doesn't seem to want to render it for me; moreover, I'm not in love with having a starting page that is just "app" (or whatever I give the app in the end) as the namespace... I want its members to be in the index as well. Here's my attempt (forgive the silly examples!):
/**
* Application Namespace for this marvellous application
*
* #namespace app
*/
var app = app || {};
/**
* An object containing methods and parameters used for UI presentation logic
*
* #type {object}
* #memberOf app
* #property {string} title - a string used as the title of the UI
* #property {function} init - a function to initialize the UI
*/
app.ui = {
// not bothering to document this for whatever reason
title: "some title",
/**
* #memberOf app.ui
* #params {object} params - an object containing necessary initialization parameters
*/
init: function(params) {
// some initialization logic
}
}
There are two problems:
Ideally I'd like app.ui to have its own page. Is #namespace the right way to do this? It works, but visually it masquerades in the Index as being at the same level as app itself.
app.ui.init isn't documented at all.
It seems to me (and admittedly, this is probably just ignorance!) that JSDoc3 would be happier if I were to use:
app.ui.init = function() {} // (etc)
But that's going to be rather ugly as far as I'm concerned. Any pointers for the syntax I need to use to indicate nested members is what I'm after.
All,
I am trying to get a handle on doxygen tags, and have encountered the following 'issue'.
In the code shown below, if I remove the #file doxytest.c from the second line, all is well. If, however, I leave it in, the output log contains this:
/Users/bp/learn/gendoxy/gendoxy/doxytest.c:10: warning: argument 'int' of command #param is not found in the argument list of foobar0(int folder)
/Users/bp/learn/gendoxy/gendoxy/doxytest.c:10: warning: The following parameters of foobar0(int folder) are not documented:
parameter 'folder'
This makes no sense to me (should it?) This is in a '.c' file, running on a MacOS.
What am I doing wrong? -- I would like to have the #file tag, and no warnings/errors from doxygen.
Or, gasp!, is this a bug?
/*!
* #file doxytest.c
*
* #author bp
* #version 0.0.1
* #copyright (2013) we be nerds,LLC
*/
/*!
* #brief void foobar0 ( int folder )
* does little to better the world.
*
* #param [in] int folder :- one small step
*
*/
void foobar0 ( int folder )
{
for (int ii = 0; ii < folder; ii++)
{
foobar1( ii );
}
}
/*!
* #brief foobar2 ( int x )
* does half of what foobar1 does.
*
*/
void foobar1( int x )
{
return( x /2 );
}
Do not include the variable type in the doxygen comment
* #param [in] folder :- one small step
Otherwise it thinks your documenting the variable 'int', and it also thinks you forgot to document the variable 'folder'.
So yes, you should keep the #file tag. Honestly I find it strange that removing the #file tag made the warning go away.