Sub topic 6
Documenting Classes and Modules
Earlier chapters covered single functions: block comments, @param and @returns, type expressions, and @typedef. Real code is usually organized into classes and modules, so this chapter applies those tools to both. It assumes you are comfortable with ES classes, import/export, and the basic tags from the previous chapters.
The tags themselves are simple. Most of the difficulty comes from knowing where a comment attaches, which tool reads it (the jsdoc site generator, the TypeScript language service in your editor, or both), and how each tool treats the same tag.
How JSDoc Attaches Comments to a Class
A JSDoc comment documents the code that comes directly after it. A class has two natural places for a comment:
- Above the
classkeyword, where you describe what the class is for. - Above the
constructor, where you describe how to create an instance: its parameters and any errors it can throw.
The jsdoc tool merges the two. The class comment supplies the class description, and the constructor comment supplies the parameter list. Editors that use TypeScript's language service read them the same way: hovering over the class name shows the class comment, and typing new Counter( shows the constructor parameters.
Constructors and Instance Properties
Here is the Counter class from the tutorial plan:
/**
* A simple in-memory counter.
*/
export class Counter {
/**
* @param {number} [start=0] - Initial value.
*/
constructor(start = 0) {
/** @type {number} */
this.value = start;
}
/**
* Increases the counter.
* @param {number} [step=1] - Amount to add.
* @returns {number} The new value.
*/
increment(step = 1) {
this.value += step;
return this.value;
}
}Each comment has a specific job:
- The class comment holds the description only. The parameters go on the constructor, not here.
- The
@typecomment onthis.valuemakesvaluea documented instance property. Without it, thejsdoctool leavesvalueout of the generated docs. TypeScript would infernumberfromstartanyway, but the explicit type stops the inference from widening ifstartbecomes optional or nullable later. - The method comment works exactly like a function comment.
You can also declare properties as class fields. Recent versions of the jsdoc tool and TypeScript both understand a comment placed directly above a field:
export class Session {
/**
* When the session started, in milliseconds since the epoch.
* @type {number}
*/
startedAt = Date.now();
/**
* The logged-in user's id, or null for anonymous sessions.
* @type {string | null}
*/
userId = null;
}The field form is useful when a property starts as null. TypeScript would otherwise infer the type from the initial value alone, and @type {string | null} records the real intent.
Methods, Getters, Setters, and Static Members
Getters and setters show up as properties in generated docs and in editor completions. Document the getter. TypeScript takes the property type from the getter's return type, and the jsdoc tool lists the pair as a single member.
/**
* A temperature stored in Celsius.
*/
export class Temperature {
/**
* @param {number} celsius - Degrees Celsius.
*/
constructor(celsius) {
/** @type {number} */
this.celsius = celsius;
}
/**
* The temperature in Fahrenheit.
* @type {number}
*/
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) * 5 / 9;
}
/**
* Creates a Temperature from a Fahrenheit reading.
* @param {number} f - Degrees Fahrenheit.
* @returns {Temperature} A new instance.
*/
static fromFahrenheit(f) {
return new Temperature((f - 32) * 5 / 9);
}
}
const t = Temperature.fromFahrenheit(212);
console.log(t.celsius, t.fahrenheit); // 100 212For ES classes you never need @static, because both tools see the static keyword. The keyword matters in links, though. JSDoc uses namepaths to tell members apart:
| Namepath | Meaning |
|---|---|
| `Temperature#fahrenheit` | Instance member, reached through an instance |
| `Temperature.fromFahrenheit` | Static member, reached through the class |
| `Temperature~helper` | Inner member, private to the scope and not exported |
Use the correct separator in {@link} tags, for example {@link Temperature.fromFahrenheit}. A wrong separator gives a broken link in the generated site.
Visibility and Mutability
JavaScript has one real privacy mechanism, #private fields. Everything else is a convention, and JSDoc tags let you write that convention down. The two tools enforce these tags to different degrees:
| Tag | `jsdoc` HTML output | TypeScript with `checkJs` |
|---|---|---|
| `@private` | Hidden unless you run with `-p` / `--private` | Error when accessed outside the class |
| `@protected` | Shown and marked protected | Error when accessed outside the class and its subclasses |
| `@public` | Default, shown | Default |
| `@readonly` | Marked read-only | Error on assignment outside the constructor |
| `#field` | Not a documented member | Real runtime privacy; no tag needed |
export class Account {
/**
* @param {string} id - Account identifier.
*/
constructor(id) {
/**
* @readonly
* @type {string}
*/
this.id = id;
/**
* Balance in cents.
* @private
* @type {number}
*/
this.balance = 0;
}
/**
* Adds money to the account.
* @param {number} cents - Amount to deposit; must be positive.
* @returns {void}
*/
deposit(cents) {
if (cents <= 0) throw new RangeError('Deposit must be positive');
this.balance += cents;
}
}Inheritance
When a class uses extends, both tools record the relationship themselves. You only need to document what the subclass adds or changes.
import { Counter } from './counter.js';
/**
* A counter that never goes above a maximum.
* @extends Counter
*/
export class LimitedCounter extends Counter {
/**
* @param {number} max - Upper bound, inclusive.
* @param {number} [start=0] - Initial value.
*/
constructor(max, start = 0) {
super(start);
/** @readonly @type {number} */
this.max = max;
}
/**
* Increases the counter without going past the maximum.
* @override
* @param {number} [step=1] - Amount to add.
* @returns {number} The new value, capped at max.
*/
increment(step = 1) {
this.value = Math.min(this.value + step, this.max);
return this.value;
}
}Here @extends Counter is optional because the extends keyword already says the same thing. It earns its place when the base class is generic, and a later chapter on @template covers that case. @override says on purpose that the method replaces a parent method. In TypeScript 4.3 and later with noImplicitOverride turned on, a JS file that overrides a method without @override gets an error.
Two more tags come up in hierarchies:
@abstractmarks a method that subclasses must implement. Thejsdoctool labels it, but TypeScript does not enforce it in JS files, so add a runtimethrowin the base method as well.@inheritdoctells thejsdoctool to copy the parent's documentation. TypeScript-based editors already show the inherited doc when an override has no comment of its own, so you rarely need the tag for editors.
Constructor Functions in Older Code
Code written before ES2015 builds classes from functions and prototypes. Neither tool can tell a constructor function from an ordinary function, so you have to say so with @class (also spelled @constructor):
/**
* A two-dimensional point.
* @class
* @param {number} x - Horizontal position.
* @param {number} y - Vertical position.
*/
function Point(x, y) {
/** @type {number} */
this.x = x;
/** @type {number} */
this.y = y;
}
/**
* Distance from the origin.
* @returns {number}
*/
Point.prototype.length = function () {
return Math.hypot(this.x, this.y);
};
console.log(new Point(3, 4).length()); // 5Both tools recognize Point.prototype.length = ... as an instance method. In this form the parameters belong on the single function comment, because there is no separate constructor to hold them. If methods are attached somewhere the tools cannot follow, such as a helper that mixes them in, add @memberof Point# (with # for instance members) to tell the jsdoc tool where they belong.
Documenting Modules
In the jsdoc tool, a module is a file marked with @module. Once a file is marked, every export becomes a member of that module and is grouped under it in the generated site.
/**
* Helpers for formatting money values.
* @module money/format
*/
/**
* Formats cents as a currency string.
* @param {number} cents - Amount in cents.
* @param {string} [currency='USD'] - ISO 4217 currency code.
* @returns {string} The formatted amount, for example "$12.50".
*/
export function formatCents(cents, currency = 'USD') {
return new Intl.NumberFormat('en-US', { style: 'currency', currency })
.format(cents / 100);
}
/**
* Rounds to the nearest cent. Not exported, so it is an inner member.
* @param {number} value
* @returns {number}
*/
function roundCents(value) {
return Math.round(value);
}Notes on module docs:
- The module name is up to you. Most projects mirror the file path, as with
money/format. If you leave the name out, thejsdoctool takes it from the file path. - To link to an export, write
{@link module:money/format.formatCents}. Non-exported helpers such asroundCentsuse~:module:money/format~roundCents. @file(alias@fileoverview) describes the file itself without declaring a module. It works well for scripts and entry points.- TypeScript ignores
@modulefor typing purposes, because every ES module file is already a module to it. Editors still show the module comment in some hover views.
Default exports deserve a name. With export default class { ... }, the generated docs show the class as module.exports or as an anonymous entry. Write export default class Counter { ... } instead, so the docs and stack traces both show a real name.
Common Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Constructor parameters appear twice in the docs | `@param` written on both the class and the constructor | Put `@param` only on the constructor |
| Property missing from generated docs | Assigned in a method other than the constructor, with no comment | Declare it in the constructor or as a class field, with `@type` |
| Module overview appears on the first function | File comment has no `@module` or `@file` | Add the tag |
| `{@link Foo.bar}` is broken | `bar` is an instance member | Use `Foo#bar` |
| `@private` member still shows in editor completions | TypeScript only reports the error when the member is accessed from outside | Expected; use `#field` for real privacy |
Exercise
You want docs and editor hints for this constructor: constructor(name, tags = []) { this.name = name; this.tags = tags; }. Write the comments so that tags is an optional string array defaulting to empty, and so that name cannot be reassigned from outside the constructor once type checking is on.
Show answer
Put /** @param {string} name - Display name. @param {string[]} [tags=[]] - Labels. */ above the constructor. Inside it, put /** @readonly @type {string} */ above this.name = name; and /** @type {string[]} */ above this.tags = tags;. The parameter tags go on the constructor, not the class, and @readonly on the property makes TypeScript report assignments made outside the constructor.
Exercise
In the module money/format, write the {@link} target for the exported function formatCents, for the inner function roundCents, and for the instance method increment of a class Counter exported from module counter.
Show answer
Use module:money/format.formatCents for the export, module:money/format~roundCents for the inner (non-exported) function, and module:counter.Counter#increment for the instance method. . marks a static or exported member, ~ an inner member, and # an instance member.
Exercise
A file begins with the comment "/* Utilities for parsing dates. /" followed immediately by "export function parseIso(s) {...}", which has its own JSDoc comment below the first one. The generated docs show "Utilities for parsing dates." as the description of parseIso. Why, and how do you fix it?
Show answer
An untagged comment attaches to the next piece of code, so the tool treats the file description as documentation for parseIso. Add @module dates/parse (or @file) to the top comment. It then becomes module or file documentation, and parseIso keeps its own comment.